Concept behind these four lines of tricky C code

前端 未结 9 831
一向
一向 2020-12-22 14:40

Why does this code give the output C++Sucks? What is the concept behind it?

#include 

double m[] = {7709179928849219.0, 771};

i         


        
9条回答
  •  长情又很酷
    2020-12-22 14:49

    More readable version:

    double m[2] = {7709179928849219.0, 771};
    // m[0] = 7709179928849219.0;
    // m[1] = 771;    
    
    int main()
    {
        if (m[1]-- != 0)
        {
            m[0] *= 2;
            main();
        }
        else
        {
            printf((char*) m);
        }
    }
    

    It recursively calls main() 771 times.

    In the beginning, m[0] = 7709179928849219.0, which stands for C++Suc;C. In every call, m[0] gets doubled, to "repair" last two letters. In the last call, m[0] contains ASCII char representation of C++Sucks and m[1] contains only zeros, so it has a null terminator for C++Sucks string. All under assumption that m[0] is stored on 8 bytes, so each char takes 1 byte.

    Without recursion and illegal main() calling it will look like this:

    double m[] = {7709179928849219.0, 0};
    for (int i = 0; i < 771; i++)
    {
        m[0] *= 2;
    }
    printf((char*) m);
    

提交回复
热议问题