BartekPL
BartekPL

Reputation: 2420

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

Actual output : 10

Why?

Upvotes: 3

Views: 66

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

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. As it is not equal to 0 then it is contextually converted to true.

So the value of the conditional expression is the second subexpression that is b which is equal to 10.

I think you mean the following initializer in the declaration

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

Upvotes: 6

Bathsheba
Bathsheba

Reputation: 234635

The expression a * b + b + c ? b : a is grouped as

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

which accounts for the result being b. Note also that c is implicitly converted to an int with value 0.

Upvotes: 4

Related Questions