我正在学习 token 解析运算符的使用。 当我做如下的时候,
#include <stdio.h>
#define concat(a, b) a##b
int main(int argc, char** argv)
{
printf("%d\n", concat(1, 2));
system("pause");
return 0;
}
输出:12
但是当我试图将参数作为变量名传递时,
#include <stdio.h>
#define concat(a, b) a##b
int main(int argc, char** argv)
{
int x = 2;
int y = 3;
printf("%d\n", concat(x, y));
system("pause");
return 0;
}
出错了
'system' undefined; assuming extern returning int
'xy': undeclared identifier
identifier "xy" is undefined
我读入了Stackoverflow因为“C 宏实际上是在编译前展开的预处理器宏。变量‘port’直到运行时才会设置。”
好吧,那是不可能的。但是当我尝试这个时
#include <stdio.h>
#define mult(a, b) a*b
int main(int argc, char** argv)
{
int x = 2;
int y = 3;
printf("%d\n", mult(x, y));
system("pause");
return 0;
}
输出:6
为什么这个没有错误,但是##有错误
最佳答案
预处理器不懂 C 语言。
预处理器愚蠢。它不运行你的程序。它只需要代码并机械地应用您告诉他应用的更改。此更改后的代码由 C 编译器编译。
当你写作时
#define concat(a,b) a##b
...
int x=2, y=3;
int z=concat(x,y);
它不会运行程序来确定 x=2,y=3。对于预处理器,int x=2, y=3;
只是一个愚蠢的标记序列,它不理解其含义。它甚至不知道 x
和 y
是变量。它只知道 concat
表示两个标记的串联。所以它产生代码:
...
int x=2, y=3;
int z=xy;
然后进入 C 编译器。
关于c - 在 ## 运算符中将变量名称作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50897721/