<分区>
谁能帮我理解下面代码的输出:
int main()
{
int a=35;
printf("%d %d %d %d %d",a--,a,a=20,a++,a=39);
return 0;
}
输出:20 19 19 39 19
对 c 中 printf 函数中如何处理(编译)赋值的见解表示赞赏。
<分区>
谁能帮我理解下面代码的输出:
int main()
{
int a=35;
printf("%d %d %d %d %d",a--,a,a=20,a++,a=39);
return 0;
}
输出:20 19 19 39 19
对 c 中 printf 函数中如何处理(编译)赋值的见解表示赞赏。
最佳答案
这是未指定的行为。 C 标准中未指定函数参数的计算顺序,因此它可以按任何顺序发生。
人们已经在评论中为您提供了一些链接,您可以继续阅读。但总之,有一种东西叫做“序列点”。这些确保之前需要执行的所有内容都已执行,然后程序可以继续。在两个序列点之间,指令可以按任何顺序执行。
来自 C11 标准:
3.4.4:
unspecified behavior
use of an unspecified value, or other behavior where this International Standard provides two or more possibilities and imposes no further requirements on which is chosen in any instanceEXAMPLE An example of unspecified behavior is the order in which the arguments to a function are evaluated.
6.5.2.2.10 说
There is a sequence point after the evaluations of the function designator and the actual arguments but before the actual call. Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function.
换句话说,函数参数的求值之间没有顺序点,因此它们可以按照编译器认为的任何顺序求值。
为了完成答案,这也是未定义的行为,因为您尝试在两个序列点之间多次更改 a
的值。
6.5.2:
If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.84)
84) his paragraph renders undefined statement expressions such as
i = ++i + 1;
a[i++] = i;
while allowing
i = i + 1;
a[i] = i;
关于c - c中printf中的多个赋值语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11736610/