Can you print anything in C++, before entering into the main function?

前端 未结 4 2005
Happy的楠姐
Happy的楠姐 2020-12-09 12:53

Can you print anything in C++, before entering into the main function?

It is interview question in Bloomberg:

Answer :create a global varia

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 13:22

    #include 
    struct X
    {
       X() 
       {
           std::cout << "Hello before ";
       }
    } x;
    
    int main()
    {
       std::cout << "main()";
    }
    

    This well-formed C++ program prints

    Hello before main()

    You see, the C++ standard guarantees that the constructors of namespace-scope variables (in this example, it's x) will be executed before main(). Therefore, if you print something in a constructor of such an object, it will be printed before main(). QED

提交回复
热议问题