为什么++ x ++给出编译错误?

编程入门 行业动态 更新时间:2024-10-19 16:20:51
本文介绍了为什么++ 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 ++给出编译错误?

本文发布于:2023-11-09 21:01:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573422.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!