Thursday, November 12, 2015

Funny C Program:The Result Is Exactly The Same As Source Code!

Have you ever seen programs whose running results are absolutely the same as their source codes?Or do you think it is amazing for this phenomenon?Let's have a try.

//The Result Is Exactly The Same As Source Code
main(){char*a="main(){char*a=%c%s%c;printf(a,34,a,34);}";printf(a,34,a,34);}

Don't modify it,even adding a space,then run it.What surprise do you find?Is the result like the following?

The Result Is Exactly The Same As Source Code


Since finding this funny program,I try to explain it.
It seems this program is so simple,with too less code.You can say like this in a way,but in another way,do you understand this simple program?
In the main function,a character pointer,a,is defined,which points to the character string "main(){char*a=%c%s%c;printf(a,34,a,34);}".Then the statement "printf(a,34,a,34);" is run.Of course,two 'a' in the bracket point to the string.So this statement is equivalent to "printf("main(){char*a=%c%s%c;printf(a,34,a,34);}",34,"main(){char*a=%c%s%c;printf(a,34,a,34);}",34);".34 is the ASCII code of double quote,so the computer prints out the sentence:main(){char*a="main(){char*a=%c%s%c;printf(a,34,a,34);}";printf(a,34,a,34);},which is what you see on the screen,meanwhile the source code.
Is it funny?Have you learned something from this program?Enjoy it!

No comments:

Post a Comment