Assume in C++ (or C, Java, etc.) I have code like this:
int a = f() > g() ? f() : g();
which of course assigns a with the greater between return values of f() and g(). Now assuming f() and g() are themselves complex and slow, should I replace this line with something like
int f_value = f(); int g_value = g(); int a = f_value > g_value ? f_value : g_value;
so neither f() and g() will be called twice, or is the compiler (given sufficient optimization) going to do something like this for me anyway so I don't have to do anything?
This general question of course applies to many similar scenarios as well.
Ternary operators can be a more concise way in limited situations (your example is a good one). BUT they can often be abused to make code unreadable (which is a cardinal sin) = do not nest ternary operators!
Emphasis: value-selection before/after action needing values. There's a different emphasis: An if / else statement emphasises the branching first and what's to be done is secondary, while a ternary operator emphasises what's to be done over the selection of the values to do it with.
The Ternary Operator is not suitable for executing a function or several statements. In this case, if else is more appropriate. If condition is preferred in case if program requires executing only on true block. In this case, it is necessary to work around to use Ternary Operator.
There is no difference in speed.
Generally, no, the compiler won't do it – it can't, actually. Calling f and g could have side effects, and the result of the second call of either f or g might not be the same as in the first call. Imagine something like this:
int f() { static int n = 0; return ++n; }
But there are exceptions proving the rule:
Actually, a compiler is allowed to perform any optimisation it wants to – as long as the optimised code behaves exactly the same (considering any visible effects) as the completely unoptimised one.
So if the compiler can guarantee that omitting the second function call does not suppress any side effects (and only then!), it actually is allowed to optimise the second call away and most likely will do so, too, at higher optimisation levels.
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