Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a postincrement always done before a function call?

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.

like image 619
12431234123412341234123 Avatar asked Dec 08 '25 10:12

12431234123412341234123


1 Answers

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

like image 151
nielsen Avatar answered Dec 10 '25 10:12

nielsen