What is static block in c or c++?

Abhineet picture Abhineet · Jul 30, 2010 · Viewed 27.7k times · Source

I want to know that what is static block in c or c++ with an example? I know what is static but what is the difference between static and static block?

Answer

bradgonesurfing picture bradgonesurfing · Jul 30, 2010

Another alternative is that you might be looking for the analogy of a static block in Java. A block of code that is run when the application is loaded. There is no such thing in C++ but it can be faked by using the constructor of a static object.

foo.cpp:

struct StaticBlock {
    StaticBlock(){
        cout << "hello" << endl;
    }
}


static StaticBlock staticBlock;

void main(int, char * args[]){

}

HOWEVER. I've been bitten by this before as it's a subtle edge case of the C++ standard. If the static object is not reachable by any code called by main the constructor of the static object may or may not be called.

I found that with gcc hello will get output and with visual studio it will not.