宏扩展错误 [英] Error in macro expansion
问题描述
我一直试图理解宏扩展,发现第二个printf给出了一个错误.我期望第二个print语句生成与第一个相同的输出.我知道有一些函数可以进行字符串连接.我发现很难理解为什么第一个打印语句有效而第二个打印语句无效.
I have been trying to understand macro expansion and found out that the second printf gives out an error. I am expecting the second print statement to generate the same output as the first one. I know there are functions to do string concatenation. I am finding it difficult to understand why first print statement works and the second doesn't.
#define CAT(str1, str2) str1 str2
void main()
{
char *string_1 = "s1", *string_2 = "s2";
printf(CAT("s1", "s2"));
printf(CAT(string_1, string_2));
}
推荐答案
尝试手动"进行预处理:
Try to do the preprocessing "by hand":
CAT
应该带有2个输入变量,并一个接一个地打印它们,并在它们之间留一个空格.所以...如果我们对您的代码进行预处理,它将变成:
CAT
is supposed to take 2 input variables, and print them one after the other, with a space between. So... if we preprocess your code, it becomes:
void main()
{
char *string_1 = "s1", *string_2 = "s2";
printf("s1" "s2");
printf(string_1 string_2);
}
编译器将"s1""s2"
自动链接为"s1s2"
, string_1 string_2
是无效的语法.
While "s1" "s2"
is automatically concatenated to "s1s2"
by the compiler, string_1 string_2
is invalid syntax.
这篇关于宏扩展错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!