#include<stdio.h>
int main()
{
int i = 10;
printf("%d", ++(-i));
return 0;
}
This is obviously an Compilation Error as post(pre)increment/decrement take l-values. So in this case -i
is r-value BUT how and why?
#include<stdio.h>
int main()
{
int i = 10;
printf("%d", ++(-i));
return 0;
}
This is obviously an Compilation Error as post(pre)increment/decrement take l-values. So in this case -i
is r-value BUT how and why?
The unary -
operator produces a r-value. ++
cannot operate on r-value. Very right.
Now, to answer the "why", let me quote C11
, chapter §6.5.3.3
The result of the unary
-
operator is the negative of its (promoted) operand.
The "result" here, is a computed value, it is not held by any variable. In other words, as mentioned in the comments, -i
does not produce any object, so it is not an lvalue, it is considered as r-value, or non-lvalue.
The preincrement operator ++
(and other similar operators) requires an lvalue, which is an expression that not only has a type/value but also refers to an object. Roughly speaking, lvalues are things you could put on the left hand side of the =
operator (but there are some exceptions) or put after the &
(address-of) operator (but there are some exceptions here too).
The term rvalue
is slang (not defined by the language standard) for expressions which are not lvalues. In the case of -i
, i
is an object, but there is no object -i
; -i
is just the resulting value from negating the value of i
. Assigning something to -i
is not possible because there is no object/storage it refers to.