为什么下面这段C代码打印12 12 12
int main(int argc, char const *argv[]) {
int a = 2, *f1, *f2;
f1 = f2 = &a;
*f2 += *f2 += a += 2.5;
printf("%i %i %i\n", a, *f1, *f2);
return 0;
}
最佳答案
*f2 += *f2 += a += 2.5;
这一行有Undefined Behavior因为您在同一表达式中多次更改 *f2
(即 a
)的值,而没有插入序列点。 UB 意味着您的程序可能会打印“Hello World”,它可能会崩溃,它可能会打印 12 12 12
或 12 12 1029
或者它可能会开始吃掉您的大脑。不要依赖未定义的行为。
引用 C++ 标准(我知道这个问题被标记为 C,但我没有 C 标准,我知道 C 中有相同的规则)
Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.53) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.
关于c - C 中的表达式求值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6802072/