Interview Hello World explanation

后端 未结 5 951
名媛妹妹
名媛妹妹 2021-01-30 05:57

This classic ioccc entry is a Hello World program written in C. Can anyone please provide an explanation of how it works?

Original code (syntax highlighting intentionall

5条回答
  •  忘了有多久
    2021-01-30 06:19

    for loop condition

    i["]

    This expression takes advantage of the fact that array indexing is commutative in C. It is equivalent to.

    "]

    So the loop will terminate when the character at position i is \0, i.e., at the end of the string, which is 14 characters long (which happens to be the same length as "hello, world!\n"). So the for loop condition can be rewritten as:

    i != 14
    

    character arithmetic

    read('-' - '-', i++ + "hello, world!\n", '/' / '/')
    

    char is an integer type, and thus:

    • '-' - '-' is 0
    • '/' / '/' is 1

      read(0, i++ + "hello, world!\n", 1)


    After fixing all the compiler warnings (like implicit int to pointer conversion), and simplifying the things mentioned above, the code becomes:

    #include 
    
    int i = 0;
    
    void read2(int, char*, int);
    
    int main()
    {
       while (i != 14)
       {
          read2(0, i++ + "hello, world!\n", 1);
       }
    
       return 0;
    }
    
    void read2(int j, char* i, int p)
    {
       write(j / p + p, i-- - j, 1);
    }
    

    (I renamed read to read2 to avoid conflicting with the Unix read function.)

    Note that the j and p arguments to read2 are unneeded, as the function is always called with j=0 and p=1.

    #include 
    
    int i = 0;
    
    void read2(char*);
    
    int main()
    {
       while (i != 14)
       {
          read2(i++ + "hello, world!\n");
       }
    
       return 0;
    }
    
    void read2(char* i)
    {
       write(1, i--, 1);
    }
    

    The call write(1, i--, 1) writes 1 character from i to file descriptor 1 (stdout). And the postdecrement is superfluous because this i is a local variable never referenced again. So this function is equivalent to putchar(*i).

    Inlining the read2 function within the main loop gives

    #include 
    
    int i = 0;
    
    int main()
    {
       while (i != 14)
       {
          putchar(*(i++ + "hello, world!\n"));
       }
    
       return 0;
    }
    

    for which the meaning is obvious.

提交回复
热议问题