Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a variable while using a post increment in C

I have a global variable called var and a function foo. (I know it's a bad practice but sometimes it's unavoidable) I'm wondering if the C standard (I'm compiling using c99) says what happens to var if I try to execute:

long foo(){
    return var++;
}

Thanks.

like image 701
Maciej Goszczycki Avatar asked Mar 25 '13 14:03

Maciej Goszczycki


1 Answers

Short answer:

It will return a copy of var and then immediately afterwards increment the global var.

Long answer:

C11 6.5.2.4

"The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented..". /--/ The value computation of the result is sequenced before the side effect of updating the stored value of the operand.

The standard 5.1.2.3 "Program execution" specifies that all side effects must have been evaluated before the program encounters a sequence point. (Plenty of into about sequence points can be found here).

There is a sequence point after a return statement (C11 6.8/4).

This means that the expression var++ is guaranteed to be completely evaluated before any code in main() continues.

Your machine code will look like this pseudo code:

  • Store a local copy of var on the stack (or in a register etc)
  • Increase the global var with 1.
  • Return from sub routine.
  • Use "copy-of-var".

Had you used prefix increment instead, the increase operation would have been sequenced before the copy was stored.

like image 122
Lundin Avatar answered Oct 22 '22 17:10

Lundin