gpt4 book ai didi

c++ - 表达式f()>g()的值,当f&g修改同一个全局变量undefined或unspecified时?

转载 作者:可可西里 更新时间:2023-11-01 16:30:56 25 4
gpt4 key购买 nike

更新:根据用户 ecatmur 的标记,它是 In C99, is f()+g() undefined or merely unspecified? 的拷贝(尽管问题询问的是 C99,但 C++ 的答案不变)。答案是:未指定(对于这两种情况)。


考虑以下 C++14 代码片段:

int i = 0;
int x() { i++; return i;}
int y() { i++; return i;}
bool z = (x() > y()); // unspecified or undefined ?

z 的值只是未指定,还是未定义的行为?

根据我的理解(如果我错了请更正),这样的表达式:i++ > i++ 将是未定义的行为,因为我们在一对序列点之间对同一个变量进行两次变异,但是上面的情况呢(突变发生在不同的函数中)?

那这个呢:

bool z = (x() > i++);  // undefined or unspecified now ?

最佳答案

在这两种情况下,值都是未指定的,但行为是明确定义的。函数调用相对于调用它们的表达式中的其他计算不确定地排序,如 [intro.exececution] 1.9/15 中指定:

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 的访问都是按顺序进行的,给出了明确定义的行为,但是顺序是不确定的,给出了一个未指定的值。

关于c++ - 表达式f()>g()的值,当f&g修改同一个全局变量undefined或unspecified时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28816936/

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