条件导数 - C中的#define

pis*_*tal 0 c linux

我正在阅读一些C代码并被困在这里.

您可以在下面找到头文件中的代码段.

#if NUMREPS == 0
        #define REPEAT(line) REPEAT0(line);
#elif NUMREPS == 16
        #define REPEAT(line) REPEAT16(line);
#endif
Run Code Online (Sandbox Code Playgroud)

标识符的衍生物在repeat16(line);这里定义:

#define REPEAT16(line) \
    line;\
    line;\
    line;\
    line;\
    line;\
    line;\
    line;\
    line;\
    line;\
    line;\
    line;\
    line;\
    line;\
    line;\
    line;\
    line;
Run Code Online (Sandbox Code Playgroud)

这个编码片段到底有什么作用?我借助此链接来理解代码

Som*_*ude 6

预处理器是在实际编译之前运行的编译过程的一个步骤.它对宏的作用就是用宏的主体替换宏调用.因此,当预处理器看到它的"调用"时REPEAT16,它将简单地用宏的参数替换它,在体内重复16次.

这个参数line正是你传递给宏的东西,所以如果你把它称之为

REPEAT16(printf("hello\n"))
Run Code Online (Sandbox Code Playgroud)

然后编译器看到的代码将是

printf("hello\n"); printf("hello\n"); printf("hello\n"); printf("hello\n"); printf("hello\n"); printf("hello\n"); printf("hello\n"); printf("hello\n"); printf("hello\n"); printf("hello\n"); printf("hello\n"); printf("hello\n"); printf("hello\n"); printf("hello\n"); printf("hello\n"); printf("hello\n");
Run Code Online (Sandbox Code Playgroud)

\宏体中的字符只是告诉预处理器当前行继续下一行.所以整个身体将是一条线.

  • 值得注意的是`if(false)REPEAT16(printf("hello \n"));`将打印`hello` 15次. (3认同)