-2
#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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294

2 Answers2

2

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2

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.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • 1
    I think the term that's used is "value of an expression" (see footnote 64 in C11). – Kerrek SB Jun 18 '15 at 18:09
  • aaha i get it -i is modified and its not stored anywhere hence making it a r-value , which further effects the ++(post increment ) part of code.Hence compilation error. DID i get it correct ? – Abhinav Rana Jun 18 '15 at 18:19
  • @AbhinavRana: Basically, yeah. – Lightness Races in Orbit Jun 18 '15 at 18:27
  • *rvalue* isn't slang, it's used in the C++ language standard, and then somewhat abusively used in C discussions – Ben Voigt Jun 18 '15 at 18:30
  • 1
    @BenVoigt: Well it's slang as far as C is concerned. There are lots of terms from C++ that are imprecise or just wrong if used to discuss C, and "slang" seems like a good characterization of such usage. – R.. GitHub STOP HELPING ICE Jun 18 '15 at 18:37
  • @AbhinavRana: Almost. But the same would apply if it were `+i` or `i+0`, which both have the same value as `i` but are not lvalues. The key detail is that these expressions are a result of applying some (possibly trivial, nop-like) operations on `i`, and as such merely have a value but are not "the object `i`". – R.. GitHub STOP HELPING ICE Jun 18 '15 at 18:38