program that prints itself, how does it work?

后端 未结 4 1457
旧时难觅i
旧时难觅i 2020-12-29 07:42

I came across a program that prints itself on this site, i.e. it prints the program code.

The program code is:

#include 
char *program         


        
4条回答
  •  青春惊慌失措
    2020-12-29 08:33

    char *program = "#include %cchar *program = %c%s%c;%cint main()%c{%cprintf(program, 10, 34, program, 34, 10, 10, 10, 10, 10, 10);%c    return 0;%c}%c";
    

    There is a char pointer name "program" which is used to store the string and %c and %s are format specifiers for char and string arguments respectively.

    printf(program, 10, 34, program, 34, 10, 10, 10, 10, 10, 10);
    

    printf function is printing output to console, 10 here is ASCII code for NEWLINE and 34 for " printf parameters are doing

    • program , passing string to be printed
    • 10 , passing 10 ASCII code for first %c (will be converted to character newline)
    • program , passing same string again to %s in program to print same string again
    • 34 , passing 34 ASCII code for second %c (will be converted to character double qoutes)
    • 10 , passing 10 ASCII code for 3rd %c (will be converted to character newline)
    • 10 , passing 10 ASCII code for 4th %c (will be converted to character newline)
    • 10 , passing 10 ASCII code for 5th %c (will be converted to character newline)
    • 10 , passing 10 ASCII code for 6th %c (will be converted to character newline)
    • 10 , passing 10 ASCII code for 7th %c (will be converted to character newline)
    • 10 , passing 10 ASCII code for 8th %c (will be converted to character newline)

提交回复
热议问题