在C中使用后增量返回变量 [英] Returning a variable while using a post increment in C

查看:178
本文介绍了在C中使用后增量返回变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个叫做 var 的全局变量和一个函数 foo 。 (我知道这是一个不好的做法,但有时它是不可避免的)我想知道是否C标准(我正在编译使用c99)说如果我尝试使用 var 执行:

  long foo(){
return var ++;
}

谢谢。 b $ b

解决方案

简短回答:

它会返回 var 和然后立即增加全局 var



长答案:

6.5.2.4



后缀++运算符的结果是操作数的值,如
a副作用,操作数对象的值递增..。 / - /

的副作用更新操作数的存储值之前,对结果的值计算进行排序。


标准5.1.2.3程序执行指定所有的副作用必须在程序遇到序列点之前被评估。 (大量的关于序列点可以在这里找到)。



return 语句(C11 6.8 / 4)之后有一个顺序点。

这意味着表达式 var ++ 保证在main()中的任何代码继续之前被完全评估。



您的机器代码看起来像这个伪代码:


  • 存储本地副本 var 在堆栈中(或在注册表中)

  • 用1增加全局 var 。 b $ b
  • 从子例程返回。

  • 使用copy-of var



如果您使用前缀增量,则增加的操作将在副本存储之前进行排序。


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:

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

这篇关于在C中使用后增量返回变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆