Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 740
Ryan Avatar asked Nov 19 '14 16:11

Ryan


1 Answers

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

like image 54
Shafik Yaghmour Avatar answered Oct 20 '22 11:10

Shafik Yaghmour