Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you help me with a short code that can print itself?

Tags:

c

macros

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

like image 274
coqer Avatar asked Nov 20 '11 09:11

coqer


1 Answers

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.

like image 85
Mat Avatar answered Sep 29 '22 08:09

Mat