Consider the following fragment:
int a,b;
a = 1;
b = 2;
c = a++++b; // does not work!! Compilation error.
c = a++*+b; // works !!
Help me understand this behaviour.
c = a++++b;
is treated as:
c = ((a++)++)b;
which is incorrect as you are trying to increment non-lvalue.
and
c = a++*+b;
is treated as:
c = (a++)*(+b);
The cause for this behaviour is: The C language lexical analyzer is greedy.
In case 1: After the token 'a' (identifier) the lexer sees +, followed by another +, so it consumes both (as the increment operator) as part of same token. It does not make the 3rd + part of the same token as +++ is not a valid token. Similarly it groups the next two + into ++ token making it effectively same as:
c = ((a++)++)b;
which is not correct as a++ will not return a lvalue, hence you can't apply a ++ on it. Something similar to saying 5++;
But in case2: the first pair of ++ will be grouped together (as increment operator). Next the * alone will be a token as you cannot combine it with a + as *+ is not a valid token. Finally the + will a token (as unary +) effectively making your statement as:
c = (a++)*(+b);
You can override this greedy behaviour of the lexer by making use of parenthesis or whitespaces as follows:
c = a++ + +b;
c = a++ * +b;
This is effectively because of "maximum munch rule" in C.
c = a++++b;
is parsed as c = a++ ++ b;
, which is syntax error.
c = a++*+b;
is parsed as c = a++ * +b;
, which is OK.
From the C99 draft, section 6.4p4 (emphasis mine):
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With