Can you help me with a short code that can print i

2020-07-13 12:16发布

问题:

#define q(k)main(){return!puts(#k"\nq("#k")");}
q(#define q(k)main(){return!puts(#k"\nq("#k")");})

This code can print itself on the screen,however,I have a difficulty in reading it,especially that two #K,how does it work?I know how #define q(k) 2*k works,but I really have no idea about this code.Please help me to analyse it!thank you!

回答1:

Simplify the call and use your compiler's preprocessor to see what is going on:

#define q(k)main(){puts(#k"hello("#k")");}
q(argument)

Running gcc -E on that gives you:

main(){puts("argument""hello(""argument"")");}

As you can see, what happens is that the argument to the q macro gets transformed into a string (because is is used as #k - this is sometimes called "stringification"). There is no other magic going on here.



标签: c macros