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.
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:
var
on the stack (or in a register etc)var
with 1.var
".Had you used prefix increment instead, the increase operation would have been sequenced before the copy was stored.
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