Core S2 Software Solutions

Self-replicating source code!

What’s a quine? Basically it’s a self-replicating program that, when executed, prints out its own source code using varying methods. Thought it might seem trivial, think about it: how does a compiled program print out its source code? A compiled program can’t retain its own source code, since it has been converted to machine language (i.e. assembly), so what to do? Basically you have to make self references to the source code and treat it as data, which isn’t too hard with the exception of control characters (such as back-slash). Don’t forget you can’t “cheat” by loading or opening outside resources – the program must be fully self-contained in a single executable. Its a neat little programming trick that bends your mind to really think hard about string manipulation and program self-references.

Check out the following C++ code I wrote. You might get a warning with GCC or Visual Studio, but once compiled and executed, it prints the exact same characters used in the original source code.

#include <stdio.h>
int main()
	char *str = "#include <stdio.h>%cint main()%c{%c%cchar *str = %c%s%c;%c%cprintf(str, 10, 10, 10, 9, 34, str, 34, 10, 9, 10, 9, 10);%c%creturn 0;%c}";
	printf(str, 10, 10, 10, 9, 34, str, 34, 10, 9, 10, 9, 10);
	return 0;
This entry was posted in News & Updates. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


Sites map