这是一段简单的C代码,令我惊讶的是它可以成功编译(至少在我正在使用的Visual Studio 2012中)
#include <stdio.h>
#define MYCONSTANT
int main(int argc, char* argv[])
{
#ifdef MYCONSTANT // We can write anything here as comment
printf("MYCONSTANT is defined");
#else We can write any random words here without marking it as comment
printf("MYCONSTANT is not defined");
#endif
return 0;
}
问题:是否可以通过这种方式在#else
之后写东西?
答案 0 :(得分:6)
在标准C中,不允许您在#else
或#endif
之后的行中添加除注释以外的任何内容。使用计算机上的编译器,默认情况下,我会从您的代码中收到警告:
test.c: In function ‘main’:
test.c:9:11: warning: extra tokens at end of #else directive [-Wendif-labels]
#else We can write any random words here without marking it as comment
^~
如果我要求严格遵守C99,这将成为一个硬错误。
但是,原始的“ K&R” C预处理器 did 允许在#else
和#endif
之后的行上显示任意文本,并且旧程序会使用该文本。您的编译器具有向后兼容性,并允许那些旧程序进行编译而不会出错。
默认情况下,许多C编译器允许使用许多现在被认为是不好的样式或完全错误的东西,以允许旧代码继续运行。浏览Visual Studio手册,看看是否有建议的配置可用于新程序。我自己不使用VS,因此无法提供任何更具体的建议。