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

时间:2018-06-17 14:47:04

标签: c c-preprocessor

我正在学习使用令牌解析运算符。 当我这样做时,

#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

为什么这没有错误,但##出现错误

1 个答案:

答案 0 :(得分:3)

预处理器不知道C语言。

预处理器 STUPID 。它不会运行您的程序。它只需要代码并机械地应用您告诉他应用的更改。此更改的代码由C compilier编译。

当你写

#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 compilier。