c++ - 我=我++;未定义。 i = foo(i++) 是否也未定义?

标签 c++ undefined-behavior

例如:

int foo(int i) { return i; }

int main()
{
  int i = 0;

  i = i++;      // Undefined
  i = foo(i++); // ?

  return 0;
}

当前的 ISO C++ 标准对此情况有何规定?

编辑:

这就是我感到困惑的地方:

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, and they are not potentially concurrent (1.10), the behavior is undefined.

In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression

Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function.

因此,您似乎可以在赋值的左侧进行值计算(仅 i),并在右侧进行副作用(i 的修改> 来自 i++),它们之间没有相互排序。

EDIT2:

对于在这里找到自己的任何人,我发现了一个关于排序的非常好的解释here .

最佳答案

你引用中的最后一句话说“在被调用函数的执行之前或之后没有特别排序”所以问题是增量和赋值是否是“否则在函数体之前或之后专门排序。

1.9 [intro.execution] p15 有答案:

When calling a function (whether or not the function is inline), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function. [ Note: Value computations and side effects associated with different argument expressions are unsequenced. — end note ]

所以 i 的递增发生在函数体之前,而 i 的赋值发生在函数返回之后,所以它是完美定义的。

在 C++11 之前的术语中,函数调用在增量和赋值之间引入了一个序列点。

关于c++ - 我=我++;未定义。 i = foo(i++) 是否也未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31063331/

相关文章:

c++ - 缺少共享库(g++ 编译)

c++ - 函数参数是否保证在堆栈上传递?

c++ - 为什么 vector::clear 不从 vector 中删除元素?

c++ - IDE输出结果后如何保证程序停止运行

c++ - 模板函数静态变量

c++ - 顶点位置/法线/坐标无法正确渲染

c++ - 使用 nvcc (CUDA) 编译 Eigen 库

c++ - 编译器如何知道 C++ constexpr 计算不会触发未定义的行为?

c - scanf为short int的奇怪行为

c++ - 以下代码是否调用未定义行为?