Abhineet Abhineet - 1 year ago 172
C Question

What is static block in c or c++?

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 Source

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.


struct 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download