algorithmcompressioncomplexity-theoryquine

Can a program output a copy of itself


I think this might be a classic question but I am not aware of an answer. Can a program output a copy of itself, and, if so, is there a short program that does this?

I do not accept the "empty program" as an answer, and I do not accept programs that have access to there own source code. Rather, I am thinking something like this:

int main(int argc, char** argv){ printf("int main(argc, char** argv){ printf...

but I do not know how to continue...


Solution

  • Yes. A programme that can make a copy of itself is called a "quine".

    The basic idea of most quines is:

    1. You write code that takes a string literal s and prints it, while replacing occurrences (or the occurrence) of a special substring foo in s by the value of s itself.

    2. You take the entire source code of the program so far and use it as the definition for s. but you exclude the definition of s from the string, instead replacing it by foo.

    That's the general idea. The rest is string formatting details, really.