为什么++ x ++给出编译错误? [英] Why does ++x++ give compile error?

查看:196
本文介绍了为什么++ x ++给出编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与后递增和预递增运算符的返回值混淆。它返回r值或l值。

I am having confusion with the return value of post-increment and pre-increment operator.Whether it returns r-value or l-value.

    #include<iostream>
    using namespace std;
    int main(){
        int a=10;
        cout<<++a++<<"\n";
    }

以下代码会产生编译错误。

The following code give a compile error.

error: lvalue required as increment operator

为什么会出现错误?

编译器如何评估表达式 ++ a ++

How does the compiler evaluates the expression ++a++?

推荐答案

后递增表达式的结果 a ++ rvalue ;在递增之前具有 a 的值的临时变量。作为右值,您可以使用其值,但不能修改它。具体来说,你不能像编译器所说的那样应用预递增。

The result of the post-increment expression, a++ is an rvalue; a temporary with the value that a had before incrementing. As an rvalue, you can use its value, but you can't modify it. Specifically, you can't apply pre-increment it, as the compiler says.

如果你要改变优先级,先做递增:

If you were to change the precedence to do the pre-increment first:

(++a)++

那么这将编译:预增量的结果是一个表示被修改的对象的lvalue 。然而,这可能具有未定义的行为;我不确定这两个修改和值的各种用法是否排序。

then this would compile: the result of pre-increment is an lvalue denoting the object that's been modified. However, this might have undefined behaviour; I'm not sure whether the two modifications and the various uses of the value are sequenced.

摘要:不要尝试写多个副作用的棘手表达式。

Summary: don't try to write tricky expressions with multiple side-effects.

这篇关于为什么++ x ++给出编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆