Possible Duplicate:
Undefined Behavior and Sequence Points
pre fix and post fix increment in C
请解释一下这个程序如何继续打印 i=2
#include<stdio.h>
void main()
{
int i=1;
i=i+2*i--;
printf("%d",i);
}
按照逻辑,它应该评估值 3,因为 -- 1+2*1=3 但这首先评估 i-- 并更新 i 的值。为什么会发生这种情况? :S
最佳答案
修改表达式中的变量,然后将该结果分配给同一变量是未定义行为,因此您看到的任何行为在技术上都是正确的(包括重新启动计算机,或毁灭宇宙)。来自 C standard ,§6.5.2:
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.
要修复此问题,请将后自减移出表达式,如下所示:
int main() {
int i=1;
i=i+2*i;
i--;
printf("%d",i);
return 0;
}
关于c - c中的后减量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7610429/