printf() 中赋值运算符的问题

issue with assignment operator inside printf()

这是代码

int main()
{
  int x=15;
  printf("%d %d %d %d",x=1,x<20,x*1,x>10);
  return 0;
}

输出为1 1 1 1

我期待 1 1 15 1 作为输出,

x*1 等于 15 但这里 x*11 ,为什么? 使用赋值运算符或修改 printf() 内的值会导致 undefined behaviour?

您的代码产生了未定义的行为。函数参数评估不是相对于彼此排序的。这意味着在 x=1 中修改对 x 的访问与其他访问的顺序无关,例如 x*1 中的访问。行为未定义。

再一次,它是未定义的,不是因为您 "used assignment operator or modifying value inside printf()",而是因为您对变量的修改访问没有 序列 相对于其他访问相同的变量。此代码

(x = 1) + x * 1

出于同样的原因也有未定义的行为,即使其中没​​有 printf。同时,这段代码

int x, y;
printf("%d %d", x = 1, y = 5);

非常好,即使 "uses assignment operator or modifying value inside printf()".

在函数调用中,函数参数可以按任何顺序求值。

由于其中一个参数修改 x 而其他参数访问它,因此结果未定义。

The Standard states that;

Between the previous and next sequence point an 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.

它不会对子表达式施加求值顺序,除非它们之间有一个序列点,而不是要求一些未指定的求值顺序,it says that modifying an object twice produces undefined behaviour