Home > Enterprise >  Why static global variables initialized to zero, but static member variable in class not initialized
Why static global variables initialized to zero, but static member variable in class not initialized

Time:11-27

static int counter // will initalized to 0

but if I make that variable inside a class, it's not initialized and I have to initialize it outside of class

class Test {
static int counter // not initialized
}
...
Test::counter = 0; 

I know the static variables are stored in BSS segment in memory and initialized by default to 0, so why is it when I make a static in class not initialized?

CodePudding user response:

Why static global variables initialized to zero, but static member variable in class not initialized?

Because the declaration for a non-inline static data member inside the class is not a definition.

This can be seen from static data member documentation:

The static keyword is only used with the declaration of a static member, inside the class definition, but not with the definition of that static member. The declaration inside the class body is not a definition and may declare the member to be of incomplete type (other than void), including the type in which the member is declared:


Also the out of class definition Test::counter = 0; is incorrect. It should instead be int Test::counter = 0;

  •  Tags:  
  • c
  • Related