My first job out of Uni was as a programmer for a small company which manufactured network switches. One of the other programmers there challenged me to write a program which output itself without referring to the file containing the source code. The following piece of ugly C code is what I came up with.
1 2 3 4 5 6 |
#include <stdio.h> int c=10;int q=34;int p=37; char h[]="#include <stdio.h>%cint c=10;int q=34;int p=37;%cchar h[]=%c%cs%c;"; char b[]="%s%cchar b[]=%c%cs%c;%cchar s[1024];char o[1024];%cint main(){sprintf(s,h,c,c,q,p,q);sprintf(o,b,s,c,q,p,q,c,c,c);printf(o,h,b);}%c"; char s[1024];char o[1024]; int main(){sprintf(s,h,c,c,q,p,q);sprintf(o,b,s,c,q,p,q,c,c,c);printf(o,h,b);} |
Is an explanation necessary… I guess so. All variable name are kept as short as possible and formatting for to make the code readable is all but eliminated.
After the necessary includes, I define useful character codes. Carriage return, quote, percent.
1 |
int c=10;int q=34;int p=37; |
Then I craft a format string that will allow the header part of the source code to be output.
1 |
char h[]="#include %cint c=10;int q=34;int p=37;%cchar h[]=%c%cs%c;"; |
Then another format string which will be used to output the body of the source code.
1 |
char b[]="%s%cchar b[]=%c%cs%c;%cchar s[1024];char o[1024];%cint main(){sprintf(s,h,c,c,q,p,q);sprintf(o,b,s,c,q,p,q,c,c,c);printf(o,h,b);}%c"; |
Now define a couple of working strings.
1 |
char s[1024];char o[1024]; |
And finally the main function which builds the output string.
1 |
int main(){sprintf(s,h,c,c,q,p,q);sprintf(o,b,s,c,q,p,q,c,c,c);printf(o,h,b);} |
Build the header string which will result in a copy of itself.
1 |
sprintf(s,h,c,c,q,p,q); |
Build the body string with %s place holders for head string and the body format string.
1 |
sprintf(o,b,s,c,q,p,q,c,c,c); |
Output the finished string for the code.
1 |
printf(o,h,b); |
I don’t understand how it works either!