Why ++i++ gives "L-value required error" in C? [duplicate]

In below code:

main()
{
  int i = 5;
  printf("%d", ++i++);
}

This Program is giving the error "L-Value required".

Can some one tell me : Why compilation error?


Solution 1:

Because postfix operators have higher precedence than prefix operators, so the expression ++i++ is equivalent to ++(i++), that is equivalent to ++( i + 1). The compiler gives l-value error because you are applying ++ on an expression (i++) that is not a modifiable lvalue, so not a valid expression in c according to increment operator definition.

According to Dennis M. Ritchie's book: "The C Programming Language":

2.8 Increment and Decrement Operators

(page 44)

The increment and decrement operators can only be applied to variables; an expression like (i + j)++ is illegal. The operand must be a modifiable lvalue of arithmetic or pointer type.

Related: An interesting bug one may like to know about in gcc 4.4.5 is that expression j = ++(i | i); compiles that should produce l-value error. Read: j = ++(i | i); and j = ++(i & i); should an error: lvalue?

Additionally, modifying same variable more then once in an expression without an intervening sequence point causes which is undefined behavior in c and c++. To understand read Explain these undefined behaviors in i = i++ + ++i;.

Solution 2:

Generally, you should not be doing this, as it obscures the code.
The reason you're getting the error is that the post-increment has precedent and thus returns an r-value, i.e. ++i++ == ++(i++) which cannot be incremented.

However, you can use (++i)++ since the pre-increment (apparently, on VS2010) returns i itself, an l-value which can be post-incremented.