Can you print anything in C++, before entering into the main function?
It is interview question in Bloomberg:
Answer :create a global varia
#include <iostream>
using namespace std;
int b() {
cout << "before ";
return 0;
}
static int a = b();
int main() {
cout << "main\n";
}
#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
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;
}
#include <iostream>
std::ostream & o = (std::cout << "Hello\n");
int main()
{
o << "Now main() runs.\n";
}