令人困惑的C条件运算符的结果

use*_*122 -7 c c++ ternary-operator conditional-operator

int a=1,b=2,c=3;
int x=1;
int y=10;
a = x ? b : c;  
cout<< a;      // Outputs 2 (the value of b)
a = y ? b : c; 
cout<< a;      // Outputs 2 (the value of b)
Run Code Online (Sandbox Code Playgroud)

现在,看看以下内容.

a=0;
x=0;
a = x ? b : c;
cout<< a;  //   Outputs 3 (the value of c !!!!) 
Run Code Online (Sandbox Code Playgroud)

为什么这种异常行为?仅当a和x均为0时,表达式的计算结果为false,否则始终为true.请解释.

DUm*_*man 6

因为x是0.

回想一下三元运算符,如果写入则condition ? a : b返回aif condition为真,b否则.您正在使用数字,除0之外的任何数字都被视为true布尔值.

x ? b : c你的情况是0 ? 2 : 3,由于0IS false,它的计算结果为3. 3然后被分配到你的a变量,印刷-什么不寻常的事情在这里.