I know that this program is not using the static variable in an appropriate way, but it shows how to reproduce a behavior I have seen :
Main.cpp :
int main(){ MyObject* p = new MyObject(); Header::i = 5; printf("i %i\n", Header::i); p->update(); return 0; }
MyObject.cpp :
MyObject::MyObject(){ } void MyObject::update(){ printf("i %i\n", Header::i); }
Extern.h :
namespace Header { static int i; };
The output I get is :
i : 5 i : 0
Why don't I get 5
for both outputs ? Where does this 0
come from ? Could you explain how static variables work ?
A global static variable is one that can only be accessed in the file where it is created. This variable is said to have file scope. In C, the preprocessor directive #define was used to create a variable with a constant value. This still works in C++, but problems could arise.
The difference between a static variable and a global variable lies in their scope. A global variable can be accessed from anywhere inside the program while a static variable only has a block scope.
5) Static global variables and functions are also possible in C/C++. The purpose of these is to limit scope of a variable or function to a file.
Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming.
Static variables have internal linkage which effectively means they are local to the compilation unit. Since you have the static variable declared in a header included in 2 source files, you basically have 2 distinct variables: one i
local to MyObject.cpp
and another, different i
, local to main.cpp
You have one static variable per translation unit where you include the header, because static variables have internal linkage.
Where does this 0 come from ?
You've not initialized the variable in the second translation unit, and static variables are zero-initialized, that's where the 0 comes from.
In the standard (§3.6.2/2):
Variables with static storage duration (3.7.1) [...] shall be zero-initialized (8.5) before any other initialization takes place.[...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With