c - 在 ## 运算符中将变量名称作为参数传递

标签 c c-preprocessor

我正在学习 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; 只是一个愚蠢的标记序列,它不理解其含义。它甚至不知道 xy 是变量。它只知道 concat 表示两个标记的串联。所以它产生代码:

...
int x=2, y=3;
int z=xy;

然后进入 C 编译器。

关于c - 在 ## 运算符中将变量名称作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50897721/

相关文章:

c++ - 用于主机循环的 CUDA bool 变量

c - 第一次将CS50 IDE用于问题集2时的错误消息-可读性

C编程: String Copy Using Heap

c++ - X 宏中元素的条件定义

objective-c - #pragma clang 诊断的 Swift 替代方案

c - 结构指针错误

c - #define 中的方括号

c++ - C/C++ : How should preprocessor directive work on macros argument list?

c++ - 如何更改宏函数参数扩展顺序?

无法释放链表