Where are static variables stored in C and C++? Where are static variables stored in C and C++? c c

Where are static variables stored in C and C++?


Where your statics go depends on whether they are zero-initialized. zero-initialized static data goes in .BSS (Block Started by Symbol), non-zero-initialized data goes in .DATA


When a program is loaded into memory, it’s organized into different segments. One of the segment is DATA segment. The Data segment is further sub-divided into two parts:

Initialized data segment: All the global, static and constant data are stored here.
Uninitialized data segment(BSS): All the uninitialized data are stored in this segment.

Here is a diagram to explain this concept:

enter image description here


here is very good link explaining these concepts:

http://www.inf.udec.cl/~leo/teoX.pdf


In fact, a variable is tuple (storage, scope, type, address, value):

storage     :   where is it stored, for example data, stack, heap...scope       :   who can see us, for example global, local...type        :   what is our type, for example int, int*...address     :   where are we locatedvalue       :   what is our value

Local scope could mean local to either the translational unit (source file), the function or the block depending on where its defined. To make variable visible to more than one function, it definitely has to be in either DATA or the BSS area (depending on whether its initialized explicitly or not, respectively). Its then scoped accordingly to either all function(s) or function(s) within source file.