16

In C#, does anybody know why the following will compile:

int i = 1;
++i;
i++;

but this will not compile?

int i = 1;
++i++;

(Compiler error: The operand of an increment or decrement operator must be a variable, property or indexer.)

Guy
  • 62,854
  • 93
  • 248
  • 316

4 Answers4

19

you are running one of the operands on the result of the other, the result of a increment/decrement is a value - and you can not use increment/decrement on a value it has to be a variable that can be set.

Nir
  • 28,825
  • 10
  • 67
  • 103
9

For the same reason you can't say

5++;

or

f(i)++;

A function returns a value, not a variable. The increment operators also return values, but cannot be applied to values.

Bill the Lizard
  • 386,424
  • 207
  • 554
  • 861
3

My guess would be that ++i returns an integer value type, to which you then try to apply the ++ operator. Seeing as you can't write to a value type (think about 0++ and if that would make sense), the compiler will issue an error.

In other words, those statements are parsed as this sequence:

++i  (i = 2, returns 2)
2++  (nothing can happen here, because you can't write a value back into '2')
fluffels
  • 4,014
  • 7
  • 34
  • 52
-3

My guess: to avoid such ugly and unnecessary constructs. Also it would use 2 operations (2x INC) instead of one (1x ADD 2).

Yes, i know ... "but i want to increase by two and i'm a l33t g33k!"

Well, don't be a geek and write something that doesn't look like an inadvertent mistake, like this:

i += 2;
steffenj
  • 7,877
  • 10
  • 34
  • 41