这取决于您所说的“无效的 C 或 C++ 代码”是什么意思。
comment 中的文本不必符合大多数语言规则。它甚至没有被标记化。这是完全有效的:
/* This comment doesn't contain a valid sequence of preprocessing tokens
(because of the apostrophe). */
它必须遵守的唯一规则是控制评论结束位置的规则。人们经常被行 cmets 中的反斜杠换行符绊倒(事实上,SO 的语法高亮器曾经弄错了!)
// Line comment with ascii art ending with a \
Oops! This line is commented out too!
块 cmets 不嵌套的频率较低(如果只是因为每个 C 教程都会警告您):
/* you can't nest /* block comments */ these words are not commented */
另一方面,“跳过”预处理器条件“组”中的文本确实必须符合语言的某些规则。标准(C99 §6.10.1p5)的确切内容是
按顺序检查每个指令的条件。如果它评估为假(零),则该组
它控制的被跳过:指令仅通过确定的名称来处理
该指令用于跟踪嵌套条件的级别;剩下的
指令的预处理标记被忽略,其他预处理标记也是如此
组。
有两个重要的部分。首先,文本是标记化的,所以它确实必须是一个有效的预处理标记序列。
#if 0
This skipped conditional group doesn't contain a valid sequence of
preprocessing tokens (because of the apostrophe).
#endif
是语法错误。
$ gcc -fsyntax-only test.c
test.c:2:37: warning: missing terminating ' character
this skipped conditional group doesn't contain a valid sequence of
^
其次,指令仍被部分处理“以跟踪嵌套条件的级别”,这意味着您可以这样做:
#if 0 // forget this entire mess
#ifdef __linux__
do_linux_specific_thing();
#elif defined __APPLE__
do_osx_specific_thing();
#elif defined _WIN32
do_windows_specific_thing();
#endif
#endif
而你不能做这个:
#ifdef __linux__
do_linux_specific_thing();
#elif defined __APPLE__
do_osx_specific_thing();
#if 0 // forget windows
#elif defined _WIN32
do_windows_specific_thing();
#endif
#endif
(你不会得到最后一个错误,但是......
$ gcc -E -P -U__linux__ -D__APPLE__ -D_WIN32 test.c
do_osx_specific_thing();
do_windows_specific_thing();
……我不认为这就是写它的人的本意。)
许多语言指南告诉你使用#if 0 来“注释掉”你想暂时禁用的大块代码区域。他们这样说是因为块 cmets 不嵌套。如果您尝试使用块注释禁用代码区域,但该区域内有块注释,则注释将提前结束,并且代码可能无法编译。这在 C 没有行 cmets 的日子里更为重要;一些项目仅使用行 cmets 进行注释,保留块 cmets 用于禁用代码。
但是因为 #if 0 ... #endif 中的代码仍然是标记化的,并且嵌套的预处理器条件仍然必须保持平衡,所以您必须小心放置 #if 0 和 #endif 的位置。这通常不是问题,因为在你禁用它之前用于编译的代码,所以它不应该有任何导致标记化错误的东西。