13
main(a){printf(a="main(a){printf(a=%c%s%c,34,a,34);}",34,a,34);}

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

MD XF
  • 7,860
  • 7
  • 40
  • 71
Anil Arya
  • 3,100
  • 7
  • 43
  • 69

1 Answers1

21

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

 "main(a){printf(a=%c%s%c,34,a,34);}"

and the operation is the rest of the program:

 main(a){printf(a=_____,34,a,34);}

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

"main(a){printf(a=\"%s\",a);}"

as the kernel, with an unquoted kernel of

main(a){printf(a="%s",a);}

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.

Jason S
  • 184,598
  • 164
  • 608
  • 970
  • 4
    @Arya: this page has a decent explanation of how 'quines' can be constructed: http://www.madore.org/~david/computers/quine.html That might give you an idea of how the above works. – Michael Burr Dec 21 '11 at 21:20
  • @Jason Sachs--- Nice explanation sir +200 for this. – Anil Arya Dec 21 '11 at 21:56