类似的代码,例如 (a+=1)%=7;
,其中 a 是 int
多变的。
我们知道运营商 +=
或 =
不是序列点,因此我们在两个相邻的序列点之间有两个副作用。 (我们这里使用的是 cpp98 的序列点规则)
但是,+=
等赋值运算符或 =
保证返回左值 分配后 ,这意味着执行顺序在某种程度上是“定义的”。
那么这是一个未定义的行为吗?
最佳答案
(a=1)=2
在 C++11 之前未定义,如 =
运算符没有引入序列点,因此 a
在没有中间序列点的情况下修改了两次。这同样适用于 (a+=1)%=7
案文是:
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.
值得一提的是,赋值运算符的描述有缺陷:
The result of the assignment operation is the value stored in the left operand after the assignment has taken place; the result is an lvalue.
如果结果是左值,则结果不能是存储的值(即右值)。左值指定内存位置。这句话似乎暗示了一种排序关系,但无论我们如何解释它,它都没有使用术语“序列点”,因此前面关于序列点的文本适用。
如果有的话,该措辞对
(a=1) + 2
之类的表达方式产生了一些疑问。 .排序的 C++11 修订版消除了所有这些歧义。
关于c++ - (a=1)=2 在 C++98 中是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60963463/