问题
Do modern compilers optimize a piece of code like if(CONSTANT) { ... }, where CONSTANT is a literal, template argument, const variable or constexpr variable? Do they remove the whole if(0) { ... } expression or "throw out" the if(1) part in if(1) { ... }?
回答1:
This is not guaranteed but most compilers of good quality will do it.
C99 Rationale says in 6.4.9:
if (0) { /* code to be excluded */ }Many modern compilers will generate no code for this if statement.
For example with gcc (in C) an assembly dump shows that dead code with either if (0) .. else or if (1) .. else is optimized out even in -O0.
来源:https://stackoverflow.com/questions/24479991/is-ifconstant-optimized-in-c-c