I read Ken Thompson's classic paper Reflections on Trusting Trust in which he prompts users to write a Quine as an introduction to his argument (highly recommended read).
A quine is a computer program which takes no input and produces a copy of its own source code as its only output.
The naive approach is simply to want to say:
print "[insert this program's source here]"
But one quickly sees that this is impossible. I ended up writing one myself using Python but still have trouble explaining "the trick". I'm looking for an excellent explanation of why Quines are possible.
The normal trick is to use printf
such that the format-string represents the structure of the program, with a place-holder for the string itself to get the recursion you need:
The standard C example from http://www.nyx.net/~gthompso/quine.htm illustrates this quite well:
char*f="char*f=%c%s%c;main(){printf(f,34,f,34,10);}%c";main(){printf(f,34,f,34,10);}
edit: After writing this, I did a bit of searching: http://www.madore.org/~david/computers/quine.html gives a very good, more theoretical, description of what exactly quines are and why they work.