gpt4 book ai didi

c - 是否在同一表达式未定义行为中两次调用具有局部副作用的函数?

转载 作者:太空狗 更新时间:2023-10-29 16:24:45 24 4
gpt4 key购买 nike

int f() {
static int i=0;
return ++i;
}
int g() {
return f() + f();
}

g() 返回 3 还是结果 undefined

最佳答案

Chapter and verse :

6.5.2.2 Function calls
...
10     There is a sequence point after the evaluations of the function designator and the actualarguments but before the actual call. Every evaluation in the calling function (includingother function calls) that is not otherwise specifically sequenced before or after theexecution of the body of the called function is indeterminately sequenced with respect tothe execution of the called function. 94)
94) In other words, function executions do not ‘‘interleave’’ with each other

结果是每个 ++i 之间都有一个序列点,因为它是函数调用的一部分。因此,此行为是明确定义的。

它是否真的按照您的意图进行是另一回事。请注意,在某些时候,您可能会面临未定义的签名溢出风险。正如其他人指出的那样,f() - f() 可能不会给出您期望的结果(在这种情况下不能保证从左到右的评估)。

关于c - 是否在同一表达式未定义行为中两次调用具有局部副作用的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40532404/

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