Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior of static global variable

Tags:

c++

static

global

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 0come from ? Could you explain how static variables work ?

like image 474
Arcyno Avatar asked Jun 25 '15 09:06

Arcyno


People also ask

What happens when a global variable is declared as static?

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.

How are global variables different from static variables?

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.

Can a global variable be static?

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.

Why static variables are evil?

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.


2 Answers

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

like image 176
bolov Avatar answered Oct 03 '22 01:10

bolov


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.[...]

like image 22
JBL Avatar answered Oct 02 '22 23:10

JBL