It depends on whether the compiler can see foo() in the same compiler.
If optimization is enabled, if foo() is in the same compilation unit as the callers, it will probably include a call to foo() , and then optimization will be simplified to the same if (true) check as before.
If you move foo() to a separate compilation unit, embedding can no longer be done, so most compilers will no longer be able to optimize this code. (Connection time optimization can be optimized in all compilation units, but this is much less common - not all compilers support it and are generally less efficient.)
source share