Consider the follwoing fragment:
int a,b;
a = 1;
b = 2;
c = a++++b; // does not work!! Compilation error.
c = a++*+b; // works !!
Please help me understand this behaviour.
Consider the follwoing fragment:
int a,b;
a = 1;
b = 2;
c = a++++b; // does not work!! Compilation error.
c = a++*+b; // works !!
Please 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 paranthesis 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.
The same reason why we get an error in the C++ for:
vector<vector<int>>;
The >>
will be treated as one operator.