Static Variables

Normal Static Variables

When we declare normal global/local variables, they can be created static by using static keyword. Static variables once created, have a lifetime of the whole program. When local variables are created, they are said to have a lifetime of the block i.e. they are destroyed when the block is over. But static variables are destroyed when the program is over even when they are declared inside a local block.
See following example

#include <iostream>
using namespace std;

void foo()
{
    static int x = 0;
    cout<< ++x;
}
int main()
{
    foo();
    cout << endl;
    foo();
    cout << endl;
    foo();
    return 0;
}

Output of above program is

1  
2  
3  

See that there is a variable ‘x’ inside foo() function which is declared static. When foo() is called first time ‘x’ is initialized with value 0 and then incremented in next statement and printing its value.

If ‘x’ was a local variable, every time foo() is called ‘x’ would have been created and destroyed when the function hits last curly brace. Output in that case would have been

    1  
    1  
    1  

But here ‘x’ is a static variable, so it is only created once and is destroyed at the end of program. So when first foo() call ends, ‘x’ is not destroyed and when second foo() call starts compiler sees that ‘x’ is a static variable and it is still in memory so it kind of ignores the first statement of foo() and simply increments it and prints its value resulting in the output

    1  
    2  
    3  

Some Points to note 1. Local variables have a block scope and block lifetime -> created inside the block, can only be accessed inside the block and destroyed when the block is over. 2. Global variables have a program scope and program lifetime -> they are generally created at the starting of program, can be accessed anywhere inside the program, and are destroyed at the end of program (when program finishes it execution) 3. Static variables have a program lifetime and scope depends on where they are created  once a static variable is created it is destroyed at the end of program. But its scope depends on whether it is a local static variable or a global static variable. If the static variable is created inside some block, although its lifetime is throughout the program but it cannot be accessed out that block and is called local static variable. If the static variable is created outside of all block, its lifetime is throughout the program and also it can be accessed anywhere throughout the program and is called global static variable

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?