of Jon Jagger
Appeared in CVu 9.2, Jan 1997

{ yourself }

A quine [1] is a self reproducing program. In other words a program, which when run, produces as output an exact copy of its own source code [2]. If you've never written a quine, try it; it can be an enlightening experience. In C the basic problem is that for the quine to compile and run it needs a main(). Once it needs a main it must also print "main". The minimum starting code is thus:
int main(){puts("main");}
However, this is clearly not correct. The output of this is "main" when it should be "int main(){puts("main");}" If you then try to correct it like so:
int main(){puts("int main(){puts(\"main\");}");}
you'll soon realize that this won't work either. The trouble is that you have altered the quine. This line of attack leads only to endless recursion and eternal gold braids. [3] The solution, { yourself }, is based on this macro:
#define q(a) puts(#a);puts("q(" #a ")")
Note that q(a) will produce as output:
Now for these two lines to be the same as their source, it must be true that
    a === #define q(a) puts(#a);puts("q(" #a ")")
in which case the quine code is:
#define q(a) puts(#a);puts("q(" #a ")")
q(#define q(a) puts(#a);puts("q(" #a ")"))
and you're almost home and dry. You just need to ensure that there is a main():
#define q(a) main(){ puts(#a);puts("q(" #a ")"); }
q(#define q(a) main(){ puts(#a);puts("q(" #a ")");} )
So is that the end of the story? Not quite. This is not a strictly conforming C program; it calls puts() without a prototype and main does not return a value. Here is the shortest strictly conforming quine that I know of:
#define q(a)main(){return puts("#include<stdio.h>\n"#a"\nq("#a")");}
q(#define q(a)main(){return puts("#include<stdio.h>\n"#a"\nq("#a")");})

That's all for now.
Jon Jagger

[1] Coined by Harbison & Steele
[2] This definition means that the empty program is not a quine.
[3] Godel, Escher, Bach by Douglas Hofstader