Sometimes, an if
statement can be rather complicated or long, so for the sake of readability it is better to extract complicated calls before the if
.
e.g. this:
if (SomeComplicatedFunctionCall() || OtherComplicatedFunctionCall())
{
// do stuff
}
into this
bool b1 = SomeComplicatedFunctionCall();
bool b2 = OtherComplicatedFunctionCall();
if (b1 || b2)
{
//do stuff
}
(provided example is not that bad, it's just for illustration... imagine other calls with multiple arguments, etc.)
But with this extraction I lost the short circuit evaluation (SCE).
- Do I really lose SCE every time? Is there some scenario where the compiler is allowed to "optimize it" and still provide SCE?
- Are there ways of keeping the improved readability of the second snippet without losing SCE?
if
conditions, but separate lines of the formcondition ||
is idiomatic in my experience. – TheobaldOtherComplicatedFunctionCall()
might be merely a computation with no side-effects that happened to take a very long time to complete, and yet the same concerns mentioned by the OP would still apply. – Stellular*FunctionCall()
so it returns earlier, then they'd need to tell us more about it. If all this grief is only for the sake of avoiding one long line containing the nameComplicatedFunctionCall()
, then shorten that name already (or use a function pointer). – Schulman