简体   繁体   English

条件运算符奇怪的输出

[英]Conditional operator weird output

I used to belive that using conditional operator in statement like this below is OK, but it is not. 我曾经相信在下面的语句中使用条件运算符是可以的,但事实并非如此。 Is there any circumscription to use conditional operator in complex statement? 在复杂语句中是否有任何限制使用条件运算符?

#include <iostream>
using namespace std;

int main() {
    int a = 1;
    int b = 10;
    bool c = false;

    int result = a * b + b + c ? b : a;

    std::cout << result << std::endl;

    return 0;
}

Predicted output : 21 预测产量: 21

Actual output : 10 实际产量: 10

Why? 为什么?

The initializer in this declaration 本声明中的初始化程序

int result = a * b + b + c ? b : a;

is equivalent to 相当于

int result = ( a * b + b + c ) ? b : a;

The subexpression a * b + b + c evaluates to 20 . 子表达式a * b + b + c计算结果为20 As it is not equal to 0 then it is contextually converted to true . 因为它不等于0,所以它在上下文中被转换为true

So the value of the conditional expression is the second subexpression that is b which is equal to 10. 因此条件表达式的值是第二个子表达式,即b等于10。

I think you mean the following initializer in the declaration 我认为你的意思是声明中的以下初始化程序

int result = a * b + b + ( c  ? b : a );

The expression a * b + b + c ? b : a 表达式a * b + b + c ? b : a a * b + b + c ? b : a is grouped as a * b + b + c ? b : a分组

(a * b + b + c) ? b : a

which accounts for the result being b . 其结果是b Note also that c is implicitly converted to an int with value 0 . 另请注意, c隐式转换为值为0int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM