This quine I saw in an article by Ken Thompson (read here) isn't reproducing the same code. I was just curious why it's not working? is the code obsolete now?.
code of quine:
char s[] = {
'\t',
'0',
'\n',
'}',
';',
'\n',
'\n',
'/',
'*',
'\n'
};
/*
*The string s is a representation of the body
*of this program from '0'
* to the end
*/
main(){
int i;
printf("char\ts[] = {\n");
for(i = 0; s[i]; i++)
printf("\t%d, \n", s[i]);
printf("%s",s);
}
output:
char s[] = {
9,
48,
10,
125,
59,
10,
10,
47,
42,
10,
0
};
/*
These are the compiler warnings on compiling (self_reproducing.c
is the filename):
self_reproducing.c:20:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
20 | main(){
| ^~~~
self_reproducing.c: In function ‘main’:
self_reproducing.c:23:2: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
23 | printf("char\ts[] = {\n");
| ^~~~~~
self_reproducing.c:23:2: warning: incompatible implicit declaration of built-in function ‘printf’
self_reproducing.c:1:1: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
+++ |+#include <stdio.h>
1 | char s[] = {
Oops! I ignored the 213 lines deleted
line. So the question should be —what is the whole quine that is mentioned in the article?
I take that "not working" to mean not 'giving compiler warnings' - because the reasons for those are self-evident - but instead what else you wrote:
This quine [...] isn't reproducing the same code
The quine is self-reproducing, once we add back (213 lines deleted)
that the author abridged and you deleted - which represent the rest of the code, plus the 0
NUL terminator that ends the array of chars
:
/*
* The string s is a representation of the body
* of this program from '0'
* to the end
*/
Your confusion seems to stem from how the program prints the integer ASCII values of the characters in said array, but it originally declared those characters like '\t'
, '\n'
, and so on. But integers with appropriate values are valid char
s, so the code is self-reproducing, even if the elements are formatted as integers instead of 'c'
haracters as in the original source. Either way, we end up with an array of the same char
s; just that array was initialised in a different but equivalent fashion.
Why does it print them as integers? Because that is far easier/shorter than having to quote, conditionally escape, and so on for each element. It maps to the same machine code / array contents but requires a lot less faff to program the quine.
The author even wrote this!
(The purist will note that the program is not precisely a self-reproducing program, but wIll produce a self-reproducing program.)
As for the edited/added question, the whole quine would of course add the rest of the characters needed to represent the remainder of the program. The author presumably abridged the program for the purpose of being able to more easily illustrate their point, without driving it home by taking a whole page.