Why "a+++++b" can not be compiled in gcc, but "a+++b", "a++ + ++b", and "a+++ ++b" can be? [duplicate]
Possible Duplicate:
Please help me understanding the error a+++++b in C
Here is is the sample code, why "a+++++b" can not be compiled , but others can be?
#inclu开发者_JS百科de <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int a = 0;
int b = 0;
int c = 0;
c = a+++b;
printf("a+++b is: %d\n", c);
c = a = b = 0;
c = a++ + ++b;
printf("a++ + ++b is: %d\n", c);
c = b = a = 0;
c = a+++ ++b;
printf("a+++ ++b is: %d\n", c);
c = b = a = 0;
c = a+++++b; // NOTE: Can not be compiled here.
printf("a+++++b is: %d\n", c);
return 0;
}
That's because a+++++b
is parsed as a ++ ++ + b
and not as a ++ + ++ b
[C's tokenizer is greedy]. a++
returns an rvalue and you cannot apply ++
on an rvalue so you get that error.
a+++b; // parsed as a ++ + b
a+++ ++b; // parsed as a ++ + ++ b
Read about Maximal Munch Rule.
The compiler is greedy so your expression
a+++++b
will be understood as
a++ ++ +b
The +
operators cascade ... with a+++++b
, there is no l-value (memory addressable value) to add against after the addition operations are cascaded.
Put another way, a+++b
is the same as (a++) + b
. That's a valid operation. The same is true with a+++ ++b
which equates to (a++) + (++b)
. But with a+++++b
, you don't get that via the C-parser. To the parser it looks like ((a++)++) + b
, and since (a++) returns a temp, that's not an l-value that can be incremented again via the ++
operator.
# include <stdio.h>
# include <stdlib.h>
int main(int argc, char **argv)
{
int a = 0;
int b = 0;
int c = 0;
c = a+++b;
printf("a+++b is: %d\n", c);
c = a = b = 0;
c = (a++)+(++b);
printf("a++ + ++b is: %d\n", c);
c = b = a = 0;
c = (a++)+(++b);
printf("a+++ ++b is: %d\n", c);
c = b = a = 0;
c = (a++)+(++b);
printf("a+++++b is: %d\n", c);
return 0;
}
精彩评论