8

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.

Lundin
  • 195,001
  • 40
  • 254
  • 396
Maciej Goszczycki
  • 1,118
  • 10
  • 25

3 Answers3

10

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.

Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396
  • It is perhaps worth mentioning that the above "machine code" illustrates why ++ on a global variable is not thread safe. A context switch between "store copy" and "increase" that acesses `var` (either to read or to write) may cause unexpected program behavior. – Lundin Mar 25 '13 at 15:17
6

As var++ is a post-increment, it is basically something like this:

long foo(){
  long tmp = var;
  var++;
  return tmp;
}

If you use ++var instead, it will return the incremented value (as it will increment the variable before returning its value).

Ale
  • 1,727
  • 14
  • 26
2

foo() will return the current value of var, and var gets increased.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
TieDad
  • 9,143
  • 5
  • 32
  • 58