Skip to content

Instantly share code, notes, and snippets.

@cslarsen
Created December 24, 2011 11:35
Show Gist options
  • Save cslarsen/1517172 to your computer and use it in GitHub Desktop.
Save cslarsen/1517172 to your computer and use it in GitHub Desktop.
Two quines in C

In "Reflections on trusting trust" --- http://cm.bell-labs.com/who/ken/trust.html --- 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 (without cheating), loosely based on the same idea, that I wrote in C. 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:

~/devel/quine csl$ 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);put  s(p);}

Compiling and running:

~/devel/quine csl$ 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);}
@cslarsen
Copy link
Author

cslarsen commented Jan 7, 2012

Added this gist on my homepage at http://csl.sublevel3.org/two-quines-in-c/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment