Is `if(CONSTANT) { … }` optimized in C/C++? [duplicate]

孤者浪人 提交于 2019-12-18 09:06:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!