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?
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?
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 amodifiable 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;
.
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.
this line:
printf("%d",++i++)
==>
printf("%d",(++i)++)
And
==>
printf("%d",(++i)); &(++i)++ ==> (++i) = (++i) +1;
See you use (++i) as a left value.
This is because you are doing increment to a constant..
In your case
++i => 6
++i++ => 6++ //this is not possible. Gives lvalue error
++i+10 => 6+10 => 16 //this is possible
So doing ++i++ is not good. Post increment/decrement, pre increment/decrement possible only on variables. At runtime your statement will become a constant so it gives lvalue error here.
++i => 6 => i=6;
i++ => 6 => i=7;
printf("%d",i); //7
The expression ++i++
is evaluated as ++(i++)
which is illegal in C as the postfix increment returns a value and prefix incrementing on a that value makes no sense.
What you have is somewhat equivalent to: ++(5)
which is obviously illegal as you can apply prefix increment on something that's not a l-value.