我有一个名为 var
的全局变量和一个函数 foo
。 (我知道这是一种不好的做法,但有时这是不可避免的)我想知道 C 标准(我正在使用 c99 进行编译)是否说明了如果我尝试执行 var
会发生什么:
long foo(){
return var++;
}
谢谢。
最佳答案
简答:
它将返回 var
的副本,然后立即递增全局 var
。
长答案:
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.
标准 5.1.2.3“程序执行”指定所有副作用必须在程序遇到序列点之前进行评估。 (可以找到大量关于序列点的信息 here)。
return
语句后有一个序列点 (C11 6.8/4)。
这意味着表达式 var++
保证在 main() 中的任何代码继续之前被完全计算。
你的机器代码看起来像这样的伪代码:
- 将
var
的本地副本存储在堆栈(或寄存器等)中 - 将全局
var
增加 1。 - 从子例程返回。
- 使用“copy-of-
var
”。
如果您改用前缀递增,则递增操作会在副本存储之前进行排序。
关于c - 在 C 中使用后增量时返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15617638/