Quines

A Quine is a computer program which prints a copy of its own source code as its only output.

Thus it is theoretically possible to compile such a program, run it, and then have its output compiled again to produce the initial program – in an infinite loop, forever.

The shortest known C Quine (although it is unlikely to compile in the less permissive C++ compilers) is this one, which is pretty clever:

main() { char *s="main() { char *s=%c%s%c; printf(s,34,s,34); }"; printf(s,34,s,34); }

But the reason I’m actually making this post (other than the fact that it’s short and I have limited time), is because I have recently bumped into another blog post about this issue. That post presents a generic recipe for creating such a “Self printing program” along with a little theory and an example written in C#. Very interesting read.

While playing with it a little myself, I’ve come to realize that C++ is probably not the best language for writing Quines, at least not without employing the more expressive boost utilities for manipulating the output, or looping through it.
Another issue with C++ is that you can’t just go and print out stuff; You have to #include the facilities you use, you have to declare the main function, and you have to add a little extra “boilerplate code” on top of that. All of that only complicates the generated Quine (and makes it uglier).
But then again, C++ isn’t a scripting language, nor is it intended for small “clever” outputs.

Could you share a Quine in your programming language of choice?

5 thoughts on “Quines

  1. Yes, that’s kinda cool and people do ask this in interviews, I can’t believe I could come up with this by myself. but the simplest obvious solution is to print the source file itself, by using fstream.

    1. That’s true. But I would call that cheating! :) And what if the source code file is removed ?

      Indeed, I don’t think it’s an easy thing to accomplish. Especially the first time.

      1. Another cool problem I have heard is how to delete your program by itself? I still don’t know the answer but this somehow relates to the problem you have shown..

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>