How does this code work?

What are a##b and #a ?

  #define f(a,b) a##b #define g(a) #a #define h(a) g(a) main() { printf("%s\n",h(f(1,2))); //how should I interpret this?? [line 1] printf("%s\n",g(f(1,2))); //and this? [line 2] } 

How does this program work?


Output signal

 12 f(1, 2) 

Now I understand how a##b and #a . But why is the result different in two cases (line 1 and line 2)?

+6
c c-preprocessor stringification
source share
7 answers

## merges two tokens together. It can only be used in a preprocessor.

f(1,2) becomes 1 ## 2 becomes 12 .

The # operator itself builds tokens: #a becomes "a" . Therefore, g(f(1,2)) becomes "f(1,2)" when the preprocessor is executed with it.

h(f(1,2)) effectively #(1 ## 2) , which becomes #12 , which becomes "12" when the preprocessor runs through it.

+19
source share

For issues like these (as well as the more β€œreal” problems associated with the preprocessor), it’s really useful for me to really read the code after it has been preprocessed.

How to do this depends on the compiler, but with gcc you should use this:

 $ gcc -E test.c (snip) main() { printf("%s\n","12"); printf("%s\n","f(1,2)"); } 

So, you can see that the characters were both combined and turned into a string.

+5
source share

a ## b inserts the togather code.

so f (1,2) becomes 12

+4
source share

The macro f (a, b) combines its arguments, g (a) turns its arguments into a string, and h (a) is an auxiliary macro for g (a). I think it will output:

 12 f(1,2) 

The reason is that the h (a) macro causes its argument to be expanded before passing it to g (a), while g (a) will take its arguments literally without expanding them first.

+3
source share

a ## b is the string binding of the literals a and b, so f (1,2) is "12"

#a is a string literal a, so g (3) is "3"

0
source share

## - macro concatenation operator. So, for example, f(foo,bar) will be equivalent to foobar .

0
source share
  #define f (a, b) a ## b
   #define g (a) #a
   #define h (a) g (a)

So, ## combine the two parts directly together, no matter what types they are ... Give an example. printf("%d\n",f(1,2)); you get 12, which means that here f (1,2) is 12 integers.

  int a2 = 100;
     printf ("% d \ n", f (a, 2));

here f (a, 2) is a label. it points to a label in your code context, if there is no int a2 = 100 , you get compilation errors. And #a turns everything that is into a string ... And then h(a) g(a) This is very strange .. It looks like when you call h (a), it goes into g (a) and passes a to g (a), firstly, it interprets what a is. so before you can g (a), a is converted to f (a, b) = a ## b = 12

0
source share

All Articles