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

前端 未结 4 1972
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:19
    #include <iostream>
    using namespace std;
    
    int b() {
      cout << "before ";
      return 0;
    }
    static int a = b();
    
    int main() {
      cout << "main\n";
    }
    
    0 讨论(0)
  • 2020-12-09 13:22
    #include <iostream>
    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

    0 讨论(0)
  • 2020-12-09 13:25

    Header file

    class A
    {
       static A* a;
    public:
       A() { cout << "A" ; }
    };
    

    Implementation file:

    A* A::a = new A;
    

    Well, statics (and not only) are initialized before the call to main.

    EDIT

    Another one:

    bool b = /*(bool)*/printf("before main");
    
    int main()
    {
       return 0;
    }
    
    0 讨论(0)
  • 2020-12-09 13:40
    #include <iostream>
    
    std::ostream & o = (std::cout << "Hello\n");
    
    int main()
    {
       o << "Now main() runs.\n";
    }
    
    0 讨论(0)
提交回复
热议问题