Another Self-reproducing C Program


The following C program is also self-reproducing, that is, if compiled and run, the output is the same as the source. In this case, the program uses more sophisticated parts of C, but it is basically easier to understand. Character strings are in red. Character constants, and special escaped characters inside strings are in blue. The line numbers at the left are not part of the source. Here is the source: quine4.c.

Deconstructing this program is going to be an exercise, after we have studied arrays of strings.

Self reproducing program: quine.c
 1 #include<stdio.h>
 2 char *a[] = {"\"};\n\n",
 3 	"main() {\n",
 4 	"  int i=0; char *b;\n",
 5 	"  printf(\"#include<stdio.h>\\nchar *a[] = {\\\"\");\n",
 6 	"  while(*a[i]) {\n",
 7 	"    for(b=a[i];*b;b++)\n",
 8 	"      switch(*b) {\n",
 9 	"         case '\\n': printf(\"\\\\n\"); break;\n",
10 	"         case '\\\\': case '\\\"': putchar('\\\\'); \n",
11 	"         default: putchar(*b);\n",
12 	"      } \n",
13 	"    printf(\"\\\",\\n\\t\\\"\"); \n",
14 	"    i++;\n",
15 	"  }\n",
16 	"  i=0;\n",
17 	"  while(*a[i]) {printf(a[i]);i++;}\n",
18 	"}\n",
19 	""};
20 
21 main() {
22   int i=0; char *b;
23   printf("#include<stdio.h>\nchar *a[] = {\"");
24   while(*a[i]) {
25     for(b=a[i];*b;b++)
26       switch(*b) {
27          case '\n': printf("\\n"); break;
28          case '\\': case '\"': putchar('\\');
29          default: putchar(*b);
30       }
31     printf("\",\n\t\"");
32     i++;
33   }
34   i=0;
35   while(*a[i]) {printf(a[i]);i++;}
36 }
% cc -o quine4 quine4.c
% quine4 > quine4_out.c
% diff quine4.c quine4_out.c


Copyright © 2011, Neal R. Wagner. Permission is granted to access, download, share, and distribute, as long as this notice remains.