后增量运算是否始终在函数调用之前执行?

huangapple go评论57阅读模式
英文:

Is a postincrement always done before a function call?

问题

考虑以下代码:

#include <stdio.h>
static int g = 3;

static int foo(int a)
{
  return g + a;
}

int main(void)
{
  printf("%i\n", foo(g++));
}

输出是否总是为7(假设 printf() 不会失败)?也就是说,标准是否保证在进入 foo() 之前会执行参数列表中的 g++ 表达式?或者编译器是否可能将 g 设置为3,调用 foo()g 仍然等于3,并在执行完 foo() 后递增 g(输出6而不是7)?

我测试过的所有编译器版本都会打印出 7,并且没有显示任何警告。但这并不意味着一定会这样。

英文:

Consider this code:

#include &lt;stdio.h&gt;
static int g=3;

static int foo(int a)
{ 
  return g+a; 
}

int main(void)
{
  printf(&quot;%i\n&quot;,foo(g++));
}

Is the output always 7 (assuming printf() will not fail)? Meaning, does the standard guarantee that the expression g++, inside the argument list for foo(), is executed before foo() is entered? Or is it possible that the compiler sets g=3 calls foo() with g==3 and increment g after the execution of foo() is done (and outputs 6 instead of 7)?

All the compiler (versions) i tests print 7 and didn't show any warnings. But that doesn't mean it has to be that way.

答案1

得分: 19

根据这里所述:

> 1) 在对所有函数参数和函数指示符进行评估之后,并在实际函数调用之前,存在一个序列点。

这确保了在调用函数之前完成g++,包括递增g

所以,是的,结果7是有保证且定义良好的。

更新: C17标准在第§6.5.2.2-10的第一句直接指出:

> 在对函数指示符和实际参数进行评估之后,但在实际调用之前,存在一个序列点。调用函数的调用函数中的每个评估(包括其他函数调用),如果没有明确定义在调用的函数体执行之前或之后与调用的函数的执行具有特定顺序,那么就是不确定顺序的。

英文:

As stated here:

> 1) There is a sequence point after the evaluation of all function arguments and of the function designator, and before the actual function call.

This guarantees that g++ is completed, including incrementing g before the function is called.

So, yes, the result 7 is guaranteed and well defined.

Update: The C17 standard states this directly in the first sentence of §6.5.2.2-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

huangapple
  • 本文由 发表于 2023年6月15日 19:06:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76481840.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定