Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "a+++++b" can not be compiled in gcc, but "a+++b", "a++ + ++b", and "a+++ ++b" can be? [duplicate]

Tags:

c

operators

gcc

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;
}
like image 355
Eric Zhang Avatar asked Apr 22 '11 06:04

Eric Zhang


2 Answers

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.

like image 75
Prasoon Saurav Avatar answered Sep 24 '22 22:09

Prasoon Saurav


The compiler is greedy so your expression

a+++++b

will be understood as

a++ ++ +b
like image 21
user237419 Avatar answered Sep 23 '22 22:09

user237419