Question

Given the following code:

 int  a=0,b=1;
 int r=a+++b;

which are the operations performed and in which order?

   a++ + b
   a + ++b

I this compiler specific or does it depend on the standard?

Was it helpful?

Solution

It is (a++) + b but not because of operator precedence.

It is parsed as (a++) + b because the compiler takes the longest token it can from a sequence of characters. In other words, the lexer keeps reading characters until it encounters something that can't be part of the same token as what it already has.

This is also how it interprets >= as one token instead of > and =, and double as 'double' not 'do uble'.

There are rules of operator precedence for statements like

a || b && c
// "a || (b && c)" NOT "(a || b) && c", because && takes precedence

However, in your case the operators ++ and + have already been determined. Once the operators have been determined, the rules of operator precedence can apply.

There are some good answers to Why doesn't a+++++b work in C? that should explain this in more detail.

OTHER TIPS

That is governed by the operator precedence. Since postfix ++ has a higher precedence than the + operator it binds tighter to a is post incremented then added to b so the result is:

(a++) + b
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top