Java – why can’t ‘a’ compile in C, but ` (a) `?

Why is + + I considered an l-value, but I + + is not? 11

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

But in Java, not 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 instead of Java?

Solution

These examples are not applicable to Java because both suffix and prefix increment operations return values rather than variables. We can see this example by going to the JLS section of postfix increment operator + +, which says:

The JLS part of prefix increment operator + + says the same thing

It's like trying to add a text value (see it live):

2++ ;
++3 ;

This gives the following error:

required: variable
found:    value

We received the same error as your example

In C prefix, increment returns an lvalue, but suffix increment returns a prvalue. Both prefix and suffix increment in C need an lvalue So your first and third C examples:

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

Because your attempt to apply prefix increment to prvalue failed And the second C example:

(++a)++;

Never mind, because the prefix increment returns an lvalue

For reference, the draft C + + standard in the suffix expression in Section 5.2 says:

And:

And the unary expression in section 5.3 says:

And:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>