Skip to content

Instantly share code, notes, and snippets.

@wernsey
Created July 26, 2016 18:48
Show Gist options
  • Save wernsey/978037f1cbcc5ac43feeb10558aa89dc to your computer and use it in GitHub Desktop.
Save wernsey/978037f1cbcc5ac43feeb10558aa89dc to your computer and use it in GitHub Desktop.
My first (only) attempt at a quine, in C
/*
* This is the annotated version of my first attempt at a Quine
*
* I wonder if it is still considered a quine if it is annotated? :)
* You'll find that if you compile and run this, the output is equivalent
* to this code, so I'm still calling it a quine.
*
* Anyway, if you don't know what a Quine is, enlighten yourself at
* the wikipedia: http://en.wikipedia.org/wiki/Quine_(computing)
*/
#include <stdio.h>
/* s contains the text representation of the program as a whole */
char*s="#include <stdio.h>\n"
"char*s=\"%s\",\n"
"*t=\"%s\";\n"
"%s\n"
"int main() \n{\n\treturn printf(s,destrip(s),destrip(t),t);\n}",
/* t contains the text description of the destrip function, below.
I take advantage of the fact that the C compiler automatically concats "string1" "string2"
to make the code more readable. If you compile it, you lose the formatting */
*t="char*destrip(char*s){"
"\n\tstatic char b[2][512];"
"\n\tstatic int c = 0;"
"\n\tchar *p;"
"\n\tfor(p=b[c++];*s;s++)"
"\n\t\tif(*s == '\\n') {*p++='\\\\';*p++='n';}"
"\n\t\telse if(*s == '\\t') {*p++='\\\\';*p++='t';}"
"\n\t\telse if(*s == '\"') {*p++='\\\\';*p++='\"';}"
"\n\t\telse if(*s == '\\\\') {*p++='\\\\';*p++='\\\\';}"
"\n\t\telse *p++=*s;"
"\n\t*p=0;"
"\n\treturn b[c-1];\n"
"}";
/* The destrip() function's purpose is to do the opposite of what the C lexical
analyser does when it reads string literals. That's to say, it replaces "\n" with "\\n"
and "\\" with "\\\\" and so on */
char*destrip(char*s){
/* The buffer in which we'll be working */
/* ugly but effective; you should have a string in b[] for each time you intend to call destrip() */
static char b[2][512];
static int c = 0; /* with which b[] are we currently working */
char *p;
for(p=b[c++];*s;s++)
if(*s == '\n') {*p++='\\';*p++='n';}
else if(*s == '\t') {*p++='\\';*p++='t';}
else if(*s == '\"') {*p++='\\';*p++='\"';}
else if(*s == '\\') {*p++='\\';*p++='\\';}
else *p++=*s;
*p=0;
return b[c-1];
}
/* Anyway, here's the main program. Compare with s above */
int main() {
return printf(s,destrip(s),destrip(t),t);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment