Doubt about statements in C / C ++ / Java

Consider the following snippet:

int a,b; a = 1; b = 2; c = a++++b; // does not work!! Compilation error. c = a++*+b; // works !! 

Please help me understand this behavior.

+6
java c ++ c operators
source share
5 answers
 c = a++++b; 

regarded as:

 c = ((a++)++)b; 

which is wrong as you try to increase non-lvalue.

and

 c = a++*+b; 

regarded as:

 c = (a++)*(+b); 

The reason for this behavior is: the lexical analyzer of the C language is greedy .

In case 1: after the token 'a' (identifier), lexer sees + followed by the other +, so it consumes both (as an increment operator) as part of the same token. It does not make the third + part of the same token as +++ is not a valid token. Similarly, it groups the following two + into + tokens, making it the same as:

 c = ((a++)++)b; 

which is wrong, since ++ does not return an lvalue, so you cannot apply ++ to it. Something like saying 5 ++;

But in case 2: the first pair ++ will be grouped (as an increment operator). Then only one * will be a token, since you cannot combine it with + as * +, it is not a valid token. Finally, + will be a token (like unary +), effectively making your statement as follows:

 c = (a++)*(+b); 

You can override this greedy lexer behavior using parentheses or spaces as follows:

 c = a++ + +b; c = a++ * +b; 
+30
source share

This is effective because of the " maximum munch rule " in C.

 c = a++++b; 

parsed as c = a++ ++ b; , which is a syntax error.

 c = a++*+b; 

parsed as c = a++ * +b; which is ok.

From draft C99, section 6.4p4 (emphasis mine):

If the input stream is parsed in the preprocessing token to the specified character, the next preprocessing token is the longest sequence of characters that can make up the preprocessing token.

+7
source share

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

 vector<vector<int>>; 

>> will be considered as one operator.

+1
source share

operator priority . ++ has a higher priority than binary +.

0
source share

limit ++ is equal to priority +. Therefore, we use from left to right.

0
source share

All Articles