Two quines in C

By Christian Stigen Larsen
Posted 24 Dec 2011 — updated 01 Dec 2013

A quine is a program that, when run, produces an exact copy of its original source code.

In Reflections on trusting trust, Ken Thompson urges the reader to try write a quine. If you haven't done so yet, please try before reading on.

Here are two quines I made wrote in C—without cheating! They are both based on the same idea. The first one is macro‐based, utilizing the ability for macros to quote parameters.

#define Q(x) #x;x
char *q=Q(main(){printf("#define Q(x) #x;x\nchar *q=Q(");printf(q);printf(")\n");})

Compiling and running it produces an exact copy of itself:

$ gcc --no-warnings shortq.c -o shortq && ./shortq
#define Q(x) #x;x
char *q=Q(main(){printf("#define Q(x) #x;x\nchar *q=Q(");printf(q);printf(")\n");})

In the next quine I tried to do away with macros. First I tried quoting program code, but then I had to quote quotation characters, and for each compilation of the next quine, the quotation degraded quickly. The trick I used was just to use putchar instead. Not extremely elegant, but simple to understand.

char*p="main(){putchar(99);putchar(104);putchar(97);putchar(114);putchar(42);putchar(112);putchar(61);putchar(34);printf(p);putchar(34);putchar(59);putchar(10);put
s(p);}";
main(){putchar(99);putchar(104);putchar(97);putchar(114);putchar(42);putchar(112);putchar(61);putchar(34);printf(p);putchar(34);putchar(59);putchar(10);puts(p);}

Compiling and running the above program produces

$ gcc --no-warnings putchar-quine.c -o p && ./p
char*p="main(){putchar(99);putchar(104);putchar(97);putchar(114);putchar(42);putchar(112);putchar(61);putchar(34);printf(p);putchar(34);putchar(59);putchar(10);puts(p);}";
main(){putchar(99);putchar(104);putchar(97);putchar(114);putchar(42);putchar(112);putchar(61);putchar(34);printf(p);putchar(34);putchar(59);putchar(10);puts(p);}

Now, let's ponder the last example for a bit. You can see that I'm just writing out a bunch of numerical codes, with some boilerplate code to get it all started. In other words, we have some driver code and then a payload of specific data we print out. We can actually create a quine out of any program. That is the main point in Thompson's article.

This document is the HTML‐version of a gist I made earlier.