C语言 #if 0
背景
C语言中#if 0
在涉及到c语言的项目时可能有人会注意到里面出现了if0这样的语句既然里面的语句永远不会被执行那为什么要留下这样的代码呢?
示例
如果有部分代码正在考虑删除或要暂时禁用,则可以使用块注释将其注释掉。
/* Block comment around whole function to keep it from getting used.
* What's even the purpose of this function?
int myUnusedFunction(void)
{
int i = 5;
return i;
}
*/
但是,如果您在块注释中包含的源代码在源代码中包含块样式注释,则现有块注释的结尾* /可能导致您的新块注释无效并导致编译问题。
/* Block comment around whole function to keep it from getting used.
* What's even the purpose of this function?
int myUnusedFunction(void)
{
int i = 5;
/* Return 5 */
return i;
}
*/
在前面的示例中,编译器可以看到函数的最后两行和最后的’* /',因此编译时会出错。一种更安全的方法是在#if 0要阻止的代码周围使用指令。
#if 0
/* #if 0 evaluates to false, so everything between here and the #endif are
* removed by the preprocessor. */
int myUnusedFunction(void)
{
int i = 5;
return i;
}
#endif
#if 0使用场景
- 临时调试使用
此指令多用在调试的时候,有段代码自己不想删除,怕后面用到所以用#if 0来暂时注释掉,如果想用的话就用#if 1来开启; - 屏蔽部分功能,必要时把#if 0改成#if 1,重新编译即可把新功能添加进来。
- 搜索
#if 0
比搜索所有注释要容易得多
总结: 一般用做调试开关。