C语言运算符

标签 c operators ternary-operator operator-precedence conditional-operator

#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) );

引用:Operator Precedence

现在,让我们将其与三元运算符条件进行比较,如 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/

相关文章:

c++ - 运算符的初始化列表和 RHS

javascript - js : Multiple return in Ternary Operator

c - 如何使用 gperf 为一系列值创建散列?

c - 终端中非常奇怪的 "fake numbers"

当父级中有 exit(0) 时,无法理解 fork() 的输出

c++ - 友元函数无法访问私有(private)数据成员

vb.net - <> 而不是在 VB.NET 中

ios - 在 Swift 三元运算符中使用 OR 操作数

PHP语法问题

c - 在 C 中的结构数组中获取唯一输入