我对运算符的优先级感到困惑,想知道如何评估此语句。
# include <stdio.h>
int main()
{
int k=35;
printf("%d %d %d",k==35,k=50,k>40);
return 0;
}
这里 k
最初的值为 35,当我在 printf
中测试 k
我认为:
k>40
应检查结果应为 0k==35
应该被检查并且结果应该是 1- 最后 50 应该分配给
k
并且应该输出 50
所以最终输出应该是1 50 0
,但是输出是0 50 1
。
最佳答案
你不能依赖这个程序的输出,因为它是 undefined behavior
,在 C 中未指定评估顺序,因为这允许编译器更好地优化,来自 C99
草案标准部分 6.5
段落 3
:
The grouping of operators and operands is indicated by the syntax.74) Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.
它也是未定义的,因为您正在访问 k
的值并在相同的 sequence point
中分配给它.来自草案标准部分 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. Furthermore, the prior value shall be read only to determine the value to be stored.
它引用了以下未定义的代码示例:
i = ++i + 1;
a[i++] = i;
更新
关于函数调用中的逗号是否充当序列点有评论。如果我们看一下 6.5.17 Comma operator
段落 2
说:
The left operand of a comma operator is evaluated as a void expression; there is a sequence point after its evaluation.
但是段落 3
说:
EXAMPLE As indicated by the syntax, the comma operator (as described in this subclause) cannot appear in contexts where a comma is used to separate items in a list (such as arguments to functions or lists of initializers).
所以在这种情况下,逗号不会引入序列点。
关于C 编程 : Confusion between operator precedence,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18231716/