Student  Arya Student Arya - 10 months ago 64
Linux Question

Self reproducing program


How it is reproducing itself after compilation? What is the role of writing 34 in printf function?

Answer Source

34 is the ASCII character code for a double-quote (") character.

To follow up on my tangential comment (it was a reference to Hofstadter's "Godel Escher Bach"), this works because it's a quine, which is basically a recipe containing two elements: a kernel of data and an operation on that kernel, such that when the operation is complete the original recipe is reproduced. To do this, the kernel and the operation are almost identical. In the program you mention, the kernel is the string


and the operation is the rest of the program:


where ____ is the kernel. You'll note they look essentially the same: the operation can print itself by using the kernel as a format specifier (which prints the kernel but unquoted, thus transforming the kernel into the operation in the output), and also feeding the kernel itself as a parameter in the format specifier (the %s) and quoting it, yielding the kernel in the output.

operation(quoted kernel) => unquoted kernel that includes a copy of the kernel, quoted => which is the original program.

one more point: the reason it uses this 34 business is that it keeps the quoting operation easy by using a kernel without quote characters; if you tried to use


as the kernel, with an unquoted kernel of


it would be much more difficult because in order to quote the kernel, you'd have to backslash-escape the quotes in the middle of the string.