【发布时间】:2020-04-22 10:15:10
【问题描述】:
下面的代码以简单的方式解释了 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
【问题讨论】:
-
请DON'T 标记存在的每一个 C 标签。如果您在谈论 C,请仅使用
c标记。如果您在谈论特定版本,则标记该版本 only. -
完全不清楚你在问什么。你有结果,那有什么不明白的呢?
-
感谢您通知我。我以后会做的。
-
我在帖子中做了一些更新。我不明白文本是如何替换的。请再次检查帖子!
-
我不明白。
#define X(value, a) char value[10];和X(value1, 1)- 你为什么会期待char value[10]1;?why the macro consider value as the text and place 1 immediately after it?是的。宏只作用于文本。
标签: c c-preprocessor x-macros