#else预处理程序指令后的注释

Atu*_*tul 2 c c-preprocessor visual-studio-2012

这是一段简单的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;
}
Run Code Online (Sandbox Code Playgroud)

问题:以#else这种方式允许写东西吗?

zwo*_*wol 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
           ^~
Run Code Online (Sandbox Code Playgroud)

如果我要求严格遵守C99,这将成为一个严重的错误。

但是,原始的“ K&R” C预处理程序确实允许在#else和之后的行上显示任意文本#endif,而旧程序会使用该文本。您的编译器是向后兼容的,并允许这些旧程序进行编译而不会出现错误。

为了允许旧代码继续工作,许多C编译器默认允许很多现在被认为是不好的样式或完全错误的东西。浏览Visual Studio手册,看看是否有建议的配置可用于新程序。我自己不使用VS,因此无法提供任何更具体的建议。