Search code examples
c++ccompiler-optimizationboolean-expression

Can b&&0 be optimized


I know that C/C++ uses the short-circuit evaluation to evaluate the expression of boolean. For example, C/C++ will definitely evaluate the operand a before the operand b in the expression a && b, if a is false, b won't be evaluated.

Besides, I know that things like 5==6 may be totally ignored by the compiler because it is a constant expression, which can be evaluated at compile time.

But I don't know if b && 0 can be optimized by compiler? Can compiler say: OK, the evaluation of 0 is much easier than the evaluation of b, and b hasn't any side effect, so I decide to change b && 0 into 0 && b to evaluate 0 first.


Solution

  • There are two independent problems involved in your question. The first is that when a compiler "sees" that the if condition is always false (due to && 0), it can completely throw away the corresponding branch. Example translation unit:

    bool f(int);
    
    int main()
    {
      if (f(1) && 0)
        return 1;
    }
    

    With enabled optimizations, there will be very likely no machine code generated for the branch. However, the f(1) expression must be still evaluated at runtime, since the compiler cannot prove that the f(1) call has no observable behavior.

    Machine code: https://godbolt.org/z/sEMrfh

    On the contrary, if the compiler could prove that f(1) had no observable behavior, it could eliminate its call away. This has nothing to do with the order of evaluation, but with the as-if rule instead. Demo translation unit:

    static bool f(int i)
    {
      int j = i + 1;
      return true;
    }
    
    int main()
    {
      if (f(1) && 0)
        return 1;
    }
    

    Machine code: https://godbolt.org/z/scs3je