Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 298
BartekPL Avatar asked Nov 29 '25 19:11

BartekPL


2 Answers

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 );
like image 144
Vlad from Moscow Avatar answered Dec 01 '25 08:12

Vlad from Moscow


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.

like image 30
Bathsheba Avatar answered Dec 01 '25 09:12

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!