Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading