Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "trick" to writing a Quine?

Tags:

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.

like image 527
calebds Avatar asked Jan 15 '12 20:01

calebds


People also ask

How to make a quine?

One of the easiest ways to create a quine is to define a string, then put the string inside itself with string formatting.

How does a quine work?

A quine is a program which prints its own listing. This means that when the program is run, it must print out precisely those instructions which the programmer wrote as part of the program (including, of course, the instructions that do the printing, and the data used in the printing).


1 Answers

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.

like image 119
Conrad Irwin Avatar answered Sep 19 '22 06:09

Conrad Irwin