c - C 中的表达式求值

标签 c undefined-behavior expression-evaluation

为什么下面这段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 1212 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/

相关文章:

c - 文件读取返回重复两次

c - 即使满足条件,C 中的“if”语句也不会执行

php - 在 PHP 7.4 异常的源代码中有 __wakeup 有什么意义?

c++ - 根据 C++ 标准,该程序在哪个确切语句中表现出未定义的行为?

c - 在 C 中取消引用指向范围外静态数据的指针

c++ - Boost::spirit 如何解析和调用c++类函数表达式

Prolog:使用 is/2 为某些子表达式显示任意表达式的真值表

c - scanf二进制数的方法?

c - 获取未初始化指针的地址是未定义的行为吗?

java - 求解字符串格式的方程