Home >Backend Development >C++ >Why are C Static Member Variables Initialized Outside the Class Definition?
Initialization of Static Member Variables in C
In C , static member variables are initialized outside the class definition. This design choice has raised questions regarding its logical reasoning and potential legacy implications.
Reason for External Initialization
Static members must be defined in exactly one translation unit to adhere to the One-Definition Rule. If initialization were allowed within the class, multiple definitions could arise in different translation units where the header file is included.
Example
Consider the following code snippet:
struct Gizmo { static string name = "Foo"; };
If the name were to be initialized within the class, it would be defined in each translation unit that includes the header file. This would violate the One-Definition Rule.
Integral Static Members
C allows for the initialization of integral static members within the declaration. However, an external definition is still required within a single translation unit to satisfy the One-Definition Rule. This serves as a syntactic shortcut:
struct Gizmo { static const int count = 42; };
As long as the expression used in the initialization is const integral or enumeration type, can be evaluated at compile-time, and a definition exists in a single translation unit, this approach is valid. For example:
gizmo.cpp
#include "gizmo.h" const int Gizmo::count;
The above is the detailed content of Why are C Static Member Variables Initialized Outside the Class Definition?. For more information, please follow other related articles on the PHP Chinese website!