5
#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!

coqer
  • 307
  • 1
  • 9

1 Answers1

9

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • Thank you,I learn a new skill----gcc -E:),I tried as you modified before,but i don't know gcc -E,i guess it should bemain(){puts(argument"hello("argument")");},but it doesn't work.you are kind and smart. – coqer Nov 20 '11 at 10:03
  • 1
    All the quotes are added. `#k` makes a string out of the argument, `k` would put the token as is. – Mat Nov 20 '11 at 10:05