top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Static Variables in C

+13 votes
3,479 views

One of the most common question while attending interview is about the Static Variable, in this article I tried to summarize the behavior of static variable in C.

Static Variable can be understood in two different cases -
1) Static variable is Inside a Function or a Block
a. Life Time of variable is life of the program i.e. there exist even after your block is not in the execustion.
b. When the control reaches to same block or function the old value is retained
c. These variable are initialized as zero and are stored in the BSS of the process.
Example

void func() {
    static int x; // x is initialized only once with 0 across three calls of func()
    printf("%d\n", x); // outputs the value of x
    x = x + 1;
}

int main() { 
    func(); // prints 0
    func(); // prints 1
    func(); // prints 2
    return 0;
}

$./a.out 
0
1
2

2) Static Variable is Outside a function
a. When we have static variable outside of a function then one more angle is added is the variable carries a file scope.
b. If your process have multiple files then the variable can be used only in the file in which it is defined.

posted Dec 24, 2013 by Salil Agrawal

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button
why does an static variable has only file scope, while it is stored in BSS(even though it exists).
The setting a variable as static has a intention to avoid the mistake when our project has multiple file and as a good coding practice we avoid the global variables.

Keeping in BSS applies to all places where you can save space as BSS another meaning is "Better Save Space". So as per me these two serves different purpose.
You mean...It's implemented to do so, for above mentioned purposes.
Whether it has been restricted to access from other file, even though it exists in memory(until program termination) thus no saving of memory space...if i am correct.
Yes it has been implemented to do so, actually static variable is one of the most confusing part about C and C++ because of its different meaning at different context.

Now coming to BSS, bss requires less memory and compare to any other area in the process i.e heap/stack.

...