by personjerry · 3y ago · 0 comments
if (cheapCheck() && expensiveCheck()) { ... }
is not equivalent to bool cheap = cheapCheck();
bool expensive = expensiveCheck();
if (cheap && expensive) { ... }
unless we're in a lazy pure functional language.And in any case the author misidentified the problem and solution. The problem is that C++ coerces bool to int. I'm 99% sure there's a warning for that that you can turn into an error.
bool cheap = cheapCheck();
bool expensive = cheap && expensiveCheck();
if (expensive) { ... }The ability of the compiler to skip the expensive function in both cases are characteristics of a "lazy" language, ie. you can assign an expensive function to a value, but the actual function isn't run until the variable is needed. Languages like C++ can't do this because it would alter the program's behavior if cheapCheck() does return true, because suddenly it would have to call expensiveCheck() after cheapCheck() (rather than before), which is an observably different behavior for the optimization to cause.
> Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first), but overloaded operators behave like regular function calls and always evaluate both
[1] https://en.cppreference.com/w/cpp/language/operator_logical [2] https://en.wikipedia.org/wiki/Short-circuit_evaluation