gpt4 book ai didi

C++评估不明确的求和表达式

转载 作者:太空狗 更新时间:2023-10-29 20:56:11 25 4
gpt4 key购买 nike

举个例子:

int g_X;
int func() {
return ++g_X; // using g_X++ is not an option
}
int main() {
g_X = 0;
int a = g_X + func();
g_X = 0;
int b = func() + g_X;
g_X = 0; int temp = g_X;
int c = temp + func();

return 0;
}

a 和 b 都是 2,c 的期望值是 1(用 Visual Studio 2010 到 2015 测试过)。我读到总和与序列点无关(例如 https://en.wikipedia.org/wiki/Sequence_point ),因此顺序不固定。但是我认为 g_X 的值在函数调用之前被捕获。我真的处于未定义的行为领域,还是有某种方法不必使用临时变量?

最佳答案

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.

([介绍.执行]/15)

因此,在 g_X + func()func() + g_X 形式的表达式中,+ 运算符是正确的没有引入任何顺序约束,但是在 main 中对 g_X 的访问发生在 func() 的主体之前或之后,您只是无法预测哪个。这意味着行为已定义,但 a 是 1 还是 2 是不可预测的。同样,b 是 1 还是 2 是不可预测的。

关于C++评估不明确的求和表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34168897/

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