加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么`a`不能在C中编译但是`(a)`呢?

发布时间:2020-12-14 06:01:34 所属栏目:Java 来源:网络整理
导读:参见英文答案 Why is ++i considered an l-value,but i++ is not?11个 标题说的是什么.对于C,(a)确实编译.但奇怪的是,(a)不是: int main() { int a = 0; ++a++; // does not compile (++a)++; // does compile ++(a++); // does not compile} 但在Java中,并
参见英文答案 > Why is ++i considered an l-value,but i++ is not?11个
标题说的是什么.对于C,(a)确实编译.但奇怪的是,(a)不是:
int main() {
    int a = 0;
    ++a++; // does not compile
    (++a)++; // does compile
    ++(a++); // does not compile
}

但在Java中,并不是所有三个:

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

有没有理由为什么C编译这个而不是Java编译?

解决方法

这些示例都不适用于Java,因为后缀和前缀增量操作都返回值而不是变量我们可以通过转到 Postfix Increment Operator ++的 JLS部分来看到这个例子,它说:

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

Prefix Increment Operator ++的JLS部分说了同样的话.

这就像试图增加一个文字值(see it live):

2++ ;
++3 ;

这给出了以下错误:

required: variable
found:    value

我们收到的错误与您的示例相同.

在C前缀中,增量返回一个左值,但是后缀增量返回一个prvalue,C中的前缀和后缀增量都需要一个左值.所以你的第一个和第三个C例子:

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

因为您尝试将前缀增量应用于prvalue而失败.而第二个C例子:

(++a)++;

没关系,因为前缀增量返回一个左值.

作为参考,第5.2节后缀表达式中的draft C++ standard说:

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

和:

The result is a prvalue

和第5.3节一元表达式说:

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

和:

The result is the updated operand; it is an lvalue

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读