为什么我在以下 c 程序中没有得到预期的输出? [英] Why i am not getting the expected output in the following c programme?
问题描述
可能重复:
什么是“#define STR(a)#a”怎么办?
c 编程语言中的宏评估
#include <stdio.h>
#define f(a,b) a##b
#define g(a) #a
#define h(a) g(a)
int main()
{
printf("%s
",h(f(1,2)));
printf("%s
",g(f(1,2)));
return 0;
}
我希望两个 printf 的输出相同.但我得到的是不同的(如下所示)
I was expecting the output to be same for both the printf. But what I am getting is different(given below)
12
f(1,2)
有人可以详细解释是什么原因以及为什么会发生这种情况吗?
can someone explain what is the reason and why is it happening in detail?
推荐答案
我扩展了你的程序,增加了一行
I extended your program with an additional line
printf("%d
",f(1,2));
这反过来又会导致
printf("%d
",12);
(使用 gcc -E
调用).
你的两行结果是
printf("%s
","12");
printf("%s
","f(1,2)");
这里发生了什么?
f(1,2)
很清楚 - 1
和 2
只是粘在一起.
f(1,2)
is clear - 1
and 2
just get sticked together.
g(something)
只是将 something
复制为一个字符串,而不对其进行特殊处理 -> "f(1,2)"
.
g(something)
just reproduces something
as a string, without treating it specially -> "f(1,2)"
.
h(something)
反过来让 g(something)
的结果展开.
h(something)
, in turn, lets the result of g(something)
expand.
这篇关于为什么我在以下 c 程序中没有得到预期的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!