gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:18:57 25 4
gpt4 key购买 nike

例如:

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/

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