Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre and post increment/decrement operators in C#

Tags:

c#

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.)

like image 773
Guy Avatar asked Oct 06 '08 12:10

Guy


3 Answers

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.

like image 55
Nir Avatar answered Oct 02 '22 07:10

Nir


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.

like image 38
Bill the Lizard Avatar answered Oct 02 '22 07:10

Bill the Lizard


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')
like image 39
fluffels Avatar answered Oct 02 '22 05:10

fluffels