Why does `++a++` not compile in C++ but `(++a)++` does?

1.8k views Asked by At

What the title says. For C++, (++a)++ does compile. Strangely enough, though, ++(a++) does not:

int main() {
    int a = 0;
    ++a++; // does not compile
    (++a)++; // does compile
    ++(a++); // does not compile
}

But in Java, it does not for all three:

public class Test {
    public static void main(String[] args) {
        int a = 0;
        ++a++; // does not compile
        (++a)++; // does not compile
        ++(a++); // does not compile
    }
}

Is there any reason why C++ compiles this but not in Java?

1

There are 1 answers

0
Shafik Yaghmour On BEST ANSWER

None of the examples work in Java because both postfix and prefix increment operations return values not variables we can see this by going to the JLS section on Postfix Increment Operator ++ for an example and it says:

The result of the postfix increment expression is not a variable, but a value.

The JLS section for Prefix Increment Operator ++ says the same thing.

This would be like trying to increment a literal value (see it live):

2++ ;
++3 ;

which gives the following error:

required: variable
found:    value

Which is the same error we receive for your examples.

In C++ prefix increment returns an lvalue but postfix increment returns an prvalue and both prefix and postfix increment in C++ require an lvalue. So your first and third C++ example:

++a++;
++(a++)

fails because you are attempting to apply prefix increment to a prvalue. While the second C++ example:

(++a)++;

is okay because prefix increment returns an lvalue.

For reference the draft C++ standard in section 5.2 Postfix expressions says:

The value of a postfix ++ expression is the value of its operand [...] The operand shall be a modifiable lvalue

and:

The result is a prvalue

and section 5.3 Unary expressions says:

The operand of prefix ++ is modified [...] The operand shall be a modifiable lvalue

and:

The result is the updated operand; it is an lvalue