使用“##”运算符的串联问题

Issue with concatenation using `##` operator

我正在使用 ## 运算符连接两个数字。代码在我使用变量时出错,但在我直接输入时工作正常。

报错。

[Error] 'xy' undeclared (first use in this function)

#include<stdio.h>
#define join(a, b)  a##b ; 

int main()
{
int x = 10;
int y = 5;
int res ;
res = join(x, y);
printf("%d",res) ;
return 0 ;
}

工作正常:

#include<stdio.h>
#define join(a, b)  a##b ; 

int main()
{
int res ;
res = join(99, 10);
printf("%d",res) ;
return 0 ;
}

好吧,预处理器 MACROS 是文本替换,因此如果您使用变量,预处理后的代码看起来像

res = xy;

现在这个 xy 是您代码中的未定义标识符。

OTOH,当你传递整数常量时,你的代码看起来像

res = 9910;

完全正确。

详细说明 ## 运算符的工作,引用 C11,章节 §6.10.3.3(强调我的

in the replacement list of a function-like macro, a parameter is immediately preceded or followed by a ## preprocessing token, the parameter is replaced by the corresponding argument’s preprocessing token sequence; [...]

## 预处理运算符执行标记粘贴。并且在编译时检查令牌。

你觉得这个 res = join(x, y); 是什么意思?

res = xy;

C 编译器应该给出编译错误。

这个res = join(99, 10);意思是

res = 9910;

这在 C 语法中是有效的。还要记住宏不是类型安全的,所以使用这样的转换:

res = (int) join(99, 10);

如果您在像这样的东西之前声明了 xy,您的代码将是有效的:

#include<stdio.h>
#define join(a, b)  a##b ; 

int main()
{
    int xy = 100;
    int res ;
    res = (int) join(x, y);
    printf("%d",res) ;
    return 0 ;
}