Can a program output a copy of itself

前端 未结 11 1120
萌比男神i
萌比男神i 2020-12-29 23:07

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?

11条回答
  •  不思量自难忘°
    2020-12-29 23:34

    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.

提交回复
热议问题