Posted on: 16/04/2010

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 realise 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 (and makes uglier) the generated Quine.
But then again, C++ isn’t a scripting language, nor is it intended for small “clever” outputs. I also believe that such tasks work out well enough in C++. At least as well as they do in C#, Java, or any other similar language.

What do you think?


5 Responses to "Quines"

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.

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.

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..


Ow, but we need a portable solution! Could just open argv[0] and write garbage instead. 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: