Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operator always replaceable by if/else?

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?

like image 307
Christian Ammer Avatar asked Dec 02 '22 04:12

Christian Ammer


1 Answers

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.

like image 54
Kristopher Johnson Avatar answered Dec 05 '22 18:12

Kristopher Johnson