[英]Why is `x && y` not parsed as `x & (&y)`?
I'm implementing a C compiler and found a curious issue. 我正在实现一个C编译器,并发现了一个奇怪的问题。 Since &
has higher precedence than &&
, it seems reasonable to consider it as a binary-and of the first operand with the address of the second: 由于&
具有比&&
更高的优先级,因此将它视为二进制并且第一个操作数与第二个地址一起考虑似乎是合理的:
x && y = (x) & ( &(y) )
The syntax overview of the C specification seems to allow this interpretation. C规范的语法概述似乎允许这种解释。 I'm probably missing or misreading something? 我可能错过或误读了什么?
My understanding of the syntax: 我对语法的理解:
andExpression := equalityExpression | andExpression:= equalityExpression | (andExpression '&' equalityExpression) | (andExpression'&'equalityExpression)| ... ...
... ...
unaryExpression := postfixExpression | unaryExpression:= postfixExpression | ( ('&' | '*' | '+' | '-' | '~' | '!') castExpression ) | (('&'|'*'|'+'|' - '|'〜'|'!')castExpression)| ... ...
C operator expressions are parsed through something known as " maximal munch " 1) , meaning that from left to right, the compiler goes for the longest chunk of symbols that can form a valid token. C运算符表达式通过称为“ maximal munch ” 1)的方式进行解析,这意味着从左到右,编译器会查找可以形成有效标记的最长符号块。 Since x &&
is longer than x &
, the compiler picks the former. 由于x &&
比x &
,编译器会选择前者。
This is why code like x+++1
compiles, +++x
does not, but + ++x
does. 这就是为什么像x+++1
编译的代码, +++x
不编译,而+ ++x
编译的原因。
1) C11 §6.4 Lexical elements ¶4 : 1) C11§6.4词汇元素¶4 :
If the input stream has been parsed into preprocessing tokens up to a given character, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token. 如果输入流已被解析为预处理令牌直到给定字符,则下一个预处理令牌是可构成预处理令牌的最长字符序列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.