是否在同一表达式未定义行为中两次调用具有局部副作用的函数? [英] Is calling a function with local side-effects twice in the same expression undefined behavior?

查看:24
本文介绍了是否在同一表达式未定义行为中两次调用具有局部副作用的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int f() {静态 int i=0;返回++i;}int g() {返回 f() + f();}

g() 返回 3 还是结果 undefined?

解决方案

章节和诗句:

<块引用>6.5.2.2 函数调用
...
10    功能指示符和实际的评价后有一个顺序点参数但在实际调用之前.调用函数中的每个评估(包括其他函数调用)之前或之后没有特别排序的被调用函数体的执行是不确定的被调用函数的执行.94)<小时>94) 换句话说,函数的执行不会相互交错"

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

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

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

Does g() return 3 or is the result 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 actual arguments but before the actual call. 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.94)
94) In other words, function executions do not ‘‘interleave’’ with each other

Upshot is that there is a sequence point between each ++i by virtue of it being part of a function call. Thus, this behavior is well-defined.

Whether it actually does what you intend is another matter. Note that at some point you risk signed overflow, which is undefined. And as others have pointed out, f() - f() may not give the result you would expect (left to right evaluation is not guaranteed in that case).

这篇关于是否在同一表达式未定义行为中两次调用具有局部副作用的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆