Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Conditional Operator versus if-else

I have always wondered about this. Let's say we have a variable, string weight, and an input variable, int mode, which can be 1 or 0.

Is there a clear benefit to using:

weight = (mode == 1) ? "mode:1" : "mode:0";

over

if(mode == 1)
    weight = "mode:1";
else
    weight = "mode:0";

beyond code readability? Are speeds at all affected, is this handled differently by the compiler (such as the ability of certain switch statements to be converted to jump tables)?

like image 420
Collin Biedenkapp Avatar asked Aug 26 '26 15:08

Collin Biedenkapp


1 Answers

The key difference between the conditional operator and an if/else block is that the conditional operator is an expression, rather than a statement. Thus, there are few places you can use the conditional operator where you can't use an if/else. For example, initialization of constant objects, like so:

const double biasFactor = (x < 5) ? 2.5 : 6.432;

If you used if/else in this case, biasFactor would have to be non-const.

Additonally, constructor initializer lists call for expressions rather than statements as well:

X::X()
  : myData(x > 5 ? 0xCAFEBABE : OxDEADBEEF)
{
}

In this case, myData may not have any assignment operator or non-const member functions defined--its constructor may be the only way to pass any parameters to it.

Also, note that any expression can be turned into a statement by adding a semicolon at the end--the reverse is not true.

like image 67
Drew Hall Avatar answered Aug 28 '26 06:08

Drew Hall



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!