This program is a bit special to me (more on that story here), so I decided to put it as the first in my IPOP Series. This is in general considered quite an advanced problem. Its about using the nuances of a languages to write some swanky code. I don't quite remember the original source from which the solution came out, but I do know this has been around for quite a long time. Nevertheless here is the snippet as I remember it -
The entire trick to doing this is the printf statement. The idea is NOT to give the format specifier string inline in the call to the function and instead use a pre-defined string - in this case 'program'. A lesser problem is specifying the double quote character (ASCII 34). Specifying the double quote chracters in the format specified string (as the sequence - \")would render it unmatched with the main source code. Interesting the trivial solution of using the ASCII value proves to be a no brainer and elegant.
The main problem usually faced is that the format specifier must be specified as part of the format specifier itself . Try to give a nested definition and you are sure to realize that you are in trouble before long. The most interesting part of the solution is the fact that the format specifier is also one of the items to be printed. This should give a good hint as to what is possible with a language as flexible as C. Of course such code is generally deprecated for their obscurtiy but good food for thought .
It is customary in Indian colleges for senior students to rag freshmen asking them to do crazy things. In my college it was strictly prohibited (officially) but nevertheless seniors did want to have fun. I have no clue as to how, but these nice bunch of guys caught hold of some of us and hurtling technical questions in the name of ragging. Somehow they picked amonst us people who were into programming, so it was a good ice-breaker and thats how our clique formed . In fact one of my seniors who has a lazy demeanor was even lazy to appear tough . So they took charge of a few of us and until we would solve problems they would have us do some menial tasks - like in filling their drinking water jug and such menial tasks. Oh yes, a deal it was.
As I seemed to get away, I was posed with this question - "write a program in any language of your choice that would print its own source code" . I went to the extent of considering programs that would decompile themselves . With a clue to do it in C-Language I still couldn't get past the recursive print construct funda . Thats how the "Infamous Room #8 gang" of ours grew up.