Consider this code:
#include <stdio.h>
static int g=3;
static int foo(int a)
{
return g+a;
}
int main(void)
{
printf("%i\n",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.
As stated here:
- 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With