Reputation: 21538
In the following case, is the compiler allowed to optimize away the call to foo()
and\or the entire if
block?
if( foo() && 0 )
{ ... }
Upvotes: 2
Views: 160
Reputation: 272717
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&&
.
Upvotes: 14
Reputation: 21645
equivalent code:
int x = (int) foo();
if (x)
if (0)
{ ... }
can you "optimize away" the first line, for arbitrary foo? foo
may be something like
int foo() {
printf("x");
return 0;
}
Upvotes: 1
Reputation: 129524
The compiler has to perform foo
before determining that 0
means the statement in the if
isn't executed. However, if foo
is a very simple function that has no side-effects (doesn't alter any global state - and there is a long definition of that in the C and C++ standards), then it itself can be optimised away. Typically that only happens if foo
is part of the same source-code.
Upvotes: 2