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)?
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:
If you used if/else in this case,
biasFactorwould have to be non-const.Additonally, constructor initializer lists call for expressions rather than statements as well:
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.