#include <stdio.h>
int main()
{
int a=-1?2:5 + 8?4:5;
printf("%d\n",a);
return 0;
}
上面程序的输出是2。但是为什么呢?请解释一下
最佳答案
编写人类可读且可理解的代码。 (至少,尝试...)
int a=-1?2:5 + 8?4:5;
与
相同int a = (-1) ? 2 : ( 5 + ( 8 ? 4 : 5) );
现在,让我们将其与三元运算符条件进行比较,如 C11
第 §6.5.15 章中所述,
The first operand is evaluated; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated). The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand (whichever is evaluated),
所以,就你而言,
- 第一个操作数不等于零
- 因此,它计算第二个操作数,并将结果(操作数的值)返回并存储到赋值运算符的 LHS 变量中。
关于C语言运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42786988/