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?
This is called a Quine:
A quine is a computer program which takes no input and produces a copy of its own source code as its only output. The standard terms for these programs in the computability theory and computer science literature are self-replicating programs, self-reproducing programs, and self-copying programs.
A quine is a fixed point of an execution environment, when the execution environment is viewed as a function. Quines are possible in any Turing complete programming language, as a direct consequence of Kleene's recursion theorem. For amusement, programmers sometimes attempt to develop the shortest possible quine in any given programming language.
Source: Wikipedia
// save it as file.cpp
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
system("cat file.cpp");
return 0;
}
In the language invented by Jon Skeet the following operator prints "Hello, world!\n".
h
I can make a modification of this language so that the following program prints "Hello, world!\n":
Hello, world!
So that's the program that prints itself.
Oh, you feel something strange about it, while it has a precise and correct mathematical definition? That's your problem. "I won't accept..." ha! Mathematics does accept, and she's the mistress I serve, so I post this answer.
I assume you allow interpreted languages. (At some level, all languages are interpreted.) Somebody writes the interpreter, and if you are writing it, you can add to it any built-in functions you like, such as a (lispy) function (foo)
that does nothing except print "(foo)
".
Or you can add a more complex macro-type function (printMeAndMyArgs ...)
.
So the trick is in how you define the problem.
Yes. A programme that can make a copy of itself is called a "quine".
The basic idea of most quines is:
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.
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.
This is indeed a classic question!
Beyond the existence of specific quines, an important result in computability theory is that for any function you might want to compute, there exists a program that "knows its own program text", i.e. that could print itself if desired. This theorem is called Kleene's second recursion theorem.