Can a program output a copy of itself

2019-02-05 19:27发布

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...

11条回答
戒情不戒烟
2楼-- · 2019-02-05 20:07

If you write a quine, be careful that the copies don't also write copies of themselves ad infinitum and end up taking over the world.

查看更多
不美不萌又怎样
3楼-- · 2019-02-05 20:08

It's called a quine, and there's a site that collects them.

查看更多
做个烂人
4楼-- · 2019-02-05 20:09
// save it as file.cpp

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    system("cat file.cpp"); 
    return 0;
}
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-02-05 20:14

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.

查看更多
干净又极端
6楼-- · 2019-02-05 20:14

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.

查看更多
走好不送
7楼-- · 2019-02-05 20:18

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

查看更多
登录 后发表回答