Search code examples
cprintfoutputquine

Program which source code is exactly the same as its output


The more I try to understand this perplexed enigma the more I want to give up.

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

How is happening for this one-line source code to generate exactly the same output when the program executes and is there any common notion for this kind of programs?


Solution

  • This is called a Quine.

    So let's see what main() does:

    printf(s,34,s,34);
    

    34 is the ASCII code for the character " (double quote), so this is the same as:

    printf(s, '"', s, '"');
    

    The first argument to printf(3) is the format string. The string passed is:

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

    So, printf(3) will output exactly that, but note the %c, %s and %c format specifiers, which instruct printf(3) to print a character, followed by a string, followed by another character in that place, which are respectively the 2nd, 3rd and 4th arguments.

    The characters, as we saw, are both ", and the string is s again (the same string). So the program output is:

    char *s = "X"; main(){printf(s,34,s,34);}
    

    Where X is the string s in the program. So we get this as output:

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

    Which, interestingly, is the program source itself.