Why is it illegal to use both prefix and postfix at the same time?

1k views Asked by At

Why is the following code illegal?

using System;

class Program
{
    static void Main(string[] args) {
        int i = 0;
        --i++;
        Console.WriteLine(i);
    }
}

It gives me the following error on the --i++:

The operand of an increment or decrement operator must be a variable, property or indexer

I know that this code has no practical use; I'm merely curious why it is not allowed. I don't care that it can be fixed by removing that line with no other effects. As this is tagged with , please include evidence from the language specification.

3

There are 3 answers

0
CodeCaster On BEST ANSWER

From the C# specification "7.6.9 Postfix increment and decrement operators":

The operand of a postfix increment or decrement operation must be an expression classified as a variable, a property access, or an indexer access. The result of the operation is a value of the same type as the operand.

I think this answers your question.

It's also the reason you can't do i++++, nor with parentheses: (i++)++ gives the same compilation error as well.

0
MaurĂ­cio Linhares On

-- returns a value, not a variable but the operator at ++ expects it to be a variable, that's why it doesn't work.

0
Bill the Lizard On

The -- and ++ operators don't just return values, they change the variable that they operate on. No matter which order you try to evaluate --i++, the first operator returns a value, which the second operator will not be able to assign its return value back to.