gpt4 book ai didi

c++ - 错误 : Operand for operator "++" must be an lvalue

转载 作者:太空宇宙 更新时间:2023-11-04 15:04:50 25 4
gpt4 key购买 nike

在 C++ 中,

i = ++++j;

在代码中工作正常,但是当我使用时,

i = j++++;

我收到以下错误:

Operand for operator "++" must be an lvalue.

为什么会出现此错误?

最佳答案

后增要求操作数应该是一个可修改的左值,但后增的结果是prvalue (“纯”右值)不可修改,此图显示了正在发生的事情:

i = (j++)++ ;
^ ^
| |
| Result is a prvalue, not a valid operand for subsequent post-increment
Modifiable lvalue

Understanding lvalues and rvalues in C and C++如果您需要了解左值右值 之间的区别,这是一个很好的起点。来自draft C++ standard 5.2.6 Increment and decrement [expr.post.incr] 段落 1 says(强调是我的):

The value of a postfix ++ expression is the value of its operand. [ Note: the value obtained is a copy of the original value —end note ] The operand shall be a modifiable lvalue. [..] The result is a prvalue.

更新

我针对未定义的行为修改了我的语言,因为这里在 C++03C++11 方面存在差异。

虽然第一个表达式显示:

i = ++++j ;

不会生成错误,但如果这是 C++03 并且 j 是基本类型,则为 undefined behavior因为在 sequence point 中多次修改它的值未定义。 older draft standard 中的相关部分将是 5 Expressions4 ,它说:

[...]Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.

并给出了一些例子,其中之一如下:

i = ++i + 1; // the behavior is undefined

C++11 中,语言更改对同一标量对象的副作用相对于对同一对象的另一个副作用是无序的,因此行为未定义。所以这实际上在 C++11 中有很好的定义,在 1.9 Program execution 段落 15 中说:

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [...] If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

在赋值之前或之后使用 j +=2 以这种方式使用后递增和预递增不会产生可读(可维护)代码声明就足够了

关于c++ - 错误 : Operand for operator "++" must be an lvalue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18819570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com