Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't a+++++b work?

Tags:

c

lvalue

int main () {    int a = 5,b = 2;    printf("%d",a+++++b);    return 0; } 

This code gives the following error:

error: lvalue required as increment operand

But if I put spaces throughout a++ + and ++b, then it works fine.

int main () {    int a = 5,b = 2;    printf("%d",a++ + ++b);    return 0; } 

What does the error mean in the first example?

like image 545
Barshan Das Avatar asked Mar 17 '11 15:03

Barshan Das


People also ask

Do ab workouts really not work?

Do Ab Exercises Burn Belly Fat? Many people do ab exercises because they want to lose belly fat. However, the evidence suggests targeted ab exercises are not very effective.

Why am I not seeing any ab results?

Your body fat is not low enough. The most common reason for not having visible abs is simply that your body fat is not low enough, simply there is fat between your skin and muscle which is blurring or obscuring the lines and definition of your six pack.


2 Answers

Compilers are written in stages. The first stage is called the lexer and turns characters into a symbolic structure. So "++" becomes something like an enum SYMBOL_PLUSPLUS. Later, the parser stage turns this into an abstract syntax tree, but it can't change the symbols. You can affect the lexer by inserting spaces (which end symbols unless they are in quotes).

Normal lexers are greedy (with some exceptions), so your code is being interpreted as

a++ ++ +b 

The input to the parser is a stream of symbols, so your code would be something like:

[ SYMBOL_NAME(name = "a"),    SYMBOL_PLUS_PLUS,    SYMBOL_PLUS_PLUS,    SYMBOL_PLUS,    SYMBOL_NAME(name = "b")  ] 

Which the parser thinks is syntactically incorrect. (EDIT based on comments: Semantically incorrect because you cannot apply ++ to an r-value, which a++ results in)

a+++b  

is

a++ +b 

Which is ok. So are your other examples.

like image 174
Lou Franco Avatar answered Oct 13 '22 05:10

Lou Franco


printf("%d",a+++++b); is interpreted as (a++)++ + b according to the Maximal Munch Rule!.

++ (postfix) doesn't evaluate to an lvalue but it requires its operand to be an lvalue.

! 6.4/4 says the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token"

like image 37
Prasoon Saurav Avatar answered Oct 13 '22 04:10

Prasoon Saurav