Show and Tell

A Simple Quine in C

A quine is a computer program that outputs its own source code when executed.

Recently I've learned to use C macros to quote a section of source code. I thought this would make writing a quine much easier. So I tried it and here is the result.

#include<stdio.h>
#define S(a) #a
#define M(a) S(a)
#define c(a) int main() {return printf("#include<stdio.h>\n#define S(a) #a\n#define M(a) S(a)\n#define c(a) %s\nc(M(c(a)))\n", a)<0;}
c(M(c(a)))
Explanation

This program basically uses macros to simplify the stringification of the source code.

The macro S converts a token to string.

The macro M converts a macro to string. When macros are passed directly to S, only the macro name is stringified. When two levels of macros are used, as is here, the argument to M will first be expanded and then passed to S. As a result, the contents of the macro is now stringified.

The macro c produces the source code to the program. The parameter a is the argument to printf.

So now let's see how it comes together.

c(a) produces a version of the source code taking the token a as the argument to the printf function.

M(c(a)) converts that to a string.

c(M(c(a))) produces the source code that prints that string.

Comparison

This program uses 197 characters.

In comparison, the best quine listed on this page has around a third of the length.

The main reason that my quine is so much larger is the three #define macro definitions. Unlike variables names, these directives cannot be shortened.

One simple way that I can use to reduce this further is to not include the stdio.h header. The GCC compiler has builtin versions of these functions, so it would still compile. However I've kept it in order to allow it to compile without warnings.