I'm implementing a C compiler and found a curious issue. 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. I'm probably missing or misreading something?
My understanding of the syntax:
andExpression := equalityExpression | (andExpression '&' equalityExpression) | ...
...
unaryExpression := postfixExpression | ( ('&' | '*' | '+' | '-' | '~' | '!') 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. Since x &&
is longer than x &
, the compiler picks the former.
This is why code like x+++1
compiles, +++x
does not, but + ++x
does.
1) C11 §6.4 Lexical elements ¶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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.