Quine - a self-replicating program

Quines are computer programs that accept no input and write its own source code on the standard output.  This entry was taken from the Jargon File, the author is unknown.

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

Getting it to compile

To get this piece of code to compile, it needs to be put in one line, as follows:

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

It compiles just fine with modern gcc compiler, with just a few warnings -- implicit declaration of printf and undeclared return type of main.

How does it work?

First, a pointer to char f is declared and initialized.  It's pointing to a string with contents of:

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

This carefully crafted value is going to be used as the format string for the printf call.

printf(f,34,f,34,10);

A quick look at the ASCII table tells us that code 34 is a double quote (") and code 10 is a newline (\n).  Now time for the most interesting part: the f string is used also as a parameter for the format string.  So, after substituting  the occurences of %c with the appropriate characters, we end up with:

"char*f=\"%s\";main(){printf(f,34,f,34,10);}\n"

Now let's substitute the %s with the contents of f:

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

When printed by printf, this is going to be exactly the code we have started with.

I know a shortcut

Writing a quine is way easier in scripting languages, where we have access to the source code.  (Please note this is considered cheating and doesn't count as a "real" quine.)

#!/usr/bin/python3
import sys
thisfile = open(sys.argv[0])
print(thisfile.read())

This Python 3 code is quite self-explanatory -- sys.argv[0] contains the current script filename.  It is opened for reading (open()), then the entire contents is read (read()) and printed out to standard output with print().