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