Why i am not getting the expected output in the fo

2020-02-11 00:11发布

Possible Duplicate:
What does “#define STR(a) #a” do?
Macros evaluation in c programming language

#include <stdio.h>
#define f(a,b) a##b
#define g(a)   #a
#define h(a) g(a)

int main()
{
      printf("%s\n",h(f(1,2)));
      printf("%s\n",g(f(1,2)));
      return 0;
 }

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?

标签: c macros
3条回答
男人必须洒脱
2楼-- · 2020-02-11 00:38

I extended your program with an additional line

printf("%d\n",f(1,2));

which, in turn, results into

printf("%d\n",12);

(called with gcc -E).

Your two lines result into

printf("%s\n","12");
printf("%s\n","f(1,2)");

What happens here?

f(1,2) is clear - 1 and 2 just get sticked together.

g(something) just reproduces something as a string, without treating it specially -> "f(1,2)".

h(something), in turn, lets the result of g(something) expand.

查看更多
Juvenile、少年°
3楼-- · 2020-02-11 00:41

C standard states that macro arguments aren't expanded if they are stringified or concatenated. That is why g(YOUR_MACRO) YOUR_MACRO isn't expanded. However in h(YOUR_MACRO) case - h() does stringification indirectly and so it complies with C macro arguments expansion rules and is expanded further.

查看更多
叛逆
4楼-- · 2020-02-11 01:04

First one:

 printf("%s\n",h(f(1,2)));

becomes:

  g(12)

which in turn becomes

  "12"

Second one:

printf("%s\n",g(f(1,2)));

becomes

"f(1,2)"

since # converts the argument to a string parameter.

查看更多
登录 后发表回答