Returning a variable while using a post increment in C

巧了我就是萌 提交于 2019-12-23 08:56:08

问题


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.


回答1:


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.




回答2:


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).




回答3:


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



来源:https://stackoverflow.com/questions/15617638/returning-a-variable-while-using-a-post-increment-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!