Pergunta

In the following case, is the compiler allowed to optimize away the call to foo() and\or the entire if block?

if( foo() && 0 )
    { ... }
Foi útil?

Solução

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.


* (C++-only) assuming foo() doesn't return a type with an overload of operator&&.

Outras dicas

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.

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;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top