In the following case, is the compiler allowed to optimize away the call to foo()
and\or the entire if
block?
if( foo() && 0 )
{ ... }
From a standards point-of-view, the compiler must evaluate the left-hand side, i.e. foo()
must be called:
[C99, 6.5.13] Unlike the bitwise binary
&
operator, the&&
operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares equal to 0, the second operand is not evaluated.
But as it knows that the body of the if
statement can never be reached,* then it's free to omit any corresponding code for that part.
Of course, if the compiler can prove that foo()
has no observable side-effects, then it's free to optimise that call away as well. But that has little to do with the short-circuit behaviour.
foo()
doesn't return a type with an overload of operator&&
.