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?
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 );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With