5

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?

#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;      // NOTE: Can not be compiled here.
    printf("a+++++b is: %d\n", c);

    return 0;
}
Community
  • 1
  • 1
Eric Zhang
  • 547
  • 1
  • 4
  • 8

4 Answers4

13

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.

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
7

The compiler is greedy so your expression

a+++++b

will be understood as

a++ ++ +b
user237419
  • 8,829
  • 4
  • 31
  • 38
5

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.

Jason
  • 31,834
  • 7
  • 59
  • 78
-2
# 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;
}
Sourav
  • 17,065
  • 35
  • 101
  • 159
  • The OP (presumably) already knows that this would work; they wanted to know *why* `a+++++b` does not. Also, bad formatting. (Not the one who downvoted btw, just making a educated guess at why they did.) – David X Apr 22 '11 at 07:07