Until now I was thinking the conditional operator int a = b == 2 ? x1 : x2;
is always replaceable by an if/else statement.
int a;
if (b == 2)
a = x1;
else
a = x2;
And the choice between one of the two is always a matter of taste. Today I was working with a task where a reference would be useful if I could write:
int& a;
if (b == 2)
a = x1;
else
a = x2;
This is not allowed and I tried the initialization of the reference with the conditional operator. This was working and I came to realize, that the conditional operator is not always replaceable by an if/else statement.
Am I right with this conclusion?
You are correct. The conditional operator is an expression, whereas if-else
is a statement. An expression can be used where a statement can be used, but the opposite is not true.
This is a good counterexample to show when you come across somebody who insists that you should never, never, never, ever use conditional expressions, because if-else
is "simple" and conditionals are "too complicated".
When C++ gets lambda expressions, then you may be able to use a lambda with an if-else
in place of a conditional.
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