下面的代码解释了 x 宏如何在 c 编程语言中以简单的方式工作
#include <stdio.h>
// Defines four variables.
#define VARIABLES \
X(value1, 1) \
X(value2, 2) \
X(value3, 3) \
X(value4, 4)
// driver program.
int main(void)
{
// Declaration of every variable
// is done through macro.
#define X(value, a) char value[10];
VARIABLES
#undef X
// String values are accepted
// for all variables.
#define X(value, a) scanf("\n%s", value);
VARIABLES
#undef X
// Values are printed.
#define X(value, a) printf("%d) %s\n", a, value);
VARIABLES
#undef X
return 0;
}
在 c 中形成宏的定义。它只是一个文本替换工具。因此编译器将按照以下方式重新创建代码:
#include <stdio.h>
int main(void)
{
char value1[10];
char value2[10];
char value3[10];
char value4[10];
scanf("\n%s", value1);
scanf("\n%s", value2);
scanf("\n%s", value3);
scanf("\n%s", value4);
printf("%d) %s\n", 1, value1);
printf("%d) %s\n", 2, value2);
printf("%d) %s\n", 3, value3);
printf("%d) %s\n", 4, value4);
return 0;
}
预处理器将替换
VARIABLES ------> X(value1, 1) X(value2, 2) X(value3, 3) X(value4, 4)
并且它将 X(value1, 1) 替换为 char value[10]; 通过以下方式
X(value1, 1) char value[10];
----- -----
v ^
| |
+--------------------+
//how the code become like this ?
char value1[10];
//why not like this?
char value[10]1;
//or like this?
char value[10];1
//why the macro consider value as the text and place 1 immediately after it?
那么第二个参数1呢,它会被替换吗?
X(value1, 1)
---
^
|
//where is this parameter replaced with