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

What the name says. For C ++ (++a)++ , compiles. Oddly enough, ++(a++) does not:

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

But in Java, this is 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 a reason why C ++ compiles this, but not in Java?

+6
source share
1 answer

None of the examples work in Java, because postfix and prefix increment operations return values, not variables, we can see this by going to the JLS 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 the increment operator ++ operator says the same thing.

It will be like trying to increase the literal value ( see it live ):

 2++ ; ++3 ; 

which gives the following error:

 required: variable found: value 

What error we get for your examples.

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

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

fails because you are trying to apply a prefix increment to the value of prvalue. Second C ++ example:

 (++a)++; 

okay because prefix increment returns l.

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

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

and

The result is prvalue

and section 5.3 Unary expressions say:

Changed prefix operand ++ [...] operand must be modifiable lvalue

and

The result is an updated operand; it is lvalue

+11
source

Source: https://habr.com/ru/post/978413/


All Articles