program that prints itself, how does it work?

♀尐吖头ヾ 提交于 2019-11-30 06:29:30
char *program = "#include <stdio.h>%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)

Printf prints the string given as the first argument (in this case the string in *program) substituting the other arguments where you have a %s or %c

%s means the arguement is a string, %c is a character.

As the note says, it uses %s to print a copy of the program string inside the program string - hence making a copy, and uses the %c to print the characters 10 (new line) and 34 "

For a better understanding, the variable program could have been written like this:

"#include <stdio.h>\nchar *program = \"%s\";\nint main()\n..."

The idea is, that you run the program, compile it's output, run that program and so on. But this can only been done with %c values 10 for linefeed and 34 for double quote.

This can be done using File handling. Save the program with any name and put that name in the open directory in fopen command. Like my program's name is hello.cpp.

This is the following program

#include <stdio.h>
#include <iostream>
int main()
{
    FILE *fp;   
    fp=fopen("hello.cpp","r");
    char ch;
    while((ch=fgetc(fp))!=EOF)
    {
       printf("%c",ch);
     }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!