Why can't I do ++i++ in C-like languages?

Viewed 5813

Half jokingly half serious : Why can't I do ++i++ in C-like languages, specifically in C#?

I'd expect it to increment the value, use that in my expression, then increment again.

8 Answers

From C# specification:

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.

An increment operator can only be applied to a variable (and ㏇) and it returns a value (not a variable). You cannot apply increment to a value (simply because there is no variable to assign the result to) so in C# you can increment a variable only once.

The situation is actually different for C++. According to C++ specification:

prefix increment or decrement is an lvalue expression

which means that in C++ you can call increment on the result of prefix increment or decrement. I.g. the following C++ code is actually valid:

#include <iostream>

using namespace std;

int main()
{
    int i = 13;

    (--i)++;
    cout<<i<<endl;

    (++i)--;
    cout<<i<<endl;

    return 0;
}

NB: The term lvalue is used in C and C++ only. And for the sake of diversity in C the result of prefix increment is actually rvalue so you can't increment increment in C.
C# language uses term variable_reference for a similar concept:

A variable_reference is an expression that is classified as a variable. A variable_reference denotes a storage location that can be accessed both to fetch the current value and to store a new value.

Related