views:

289

answers:

5

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.

+29  A: 
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;  
codaddict
Thanks codaddict for the elaborate explanation. Anytime in doubt redging grouping of operators, I'll applying this max munching rule.
Zacky112
+7  A: 

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.

Alok
Thanks Alok for giving the reference and the explanation.
Zacky112
A: 

operator precedence. ++ has high priority than binary +.

bhups
I don't see how it could be operator precedence.
Alok
c = a++ + +b; is fine but if you remove white spaces then it turns out be an invalid lvalue error.
bhups
I guess I misunderstood the problem. thanks for the explanation.
bhups
A: 

precedance of ++ is equal to precedance of +. So we use left to right.

+1  A: 

The same reason why we get an error in the C++ for:

vector<vector<int>>;

The >> will be treated as one operator.

Coder