Dremendo Tag Line

Static Variables in C++ Programming

OOPs in C++

In this lesson, we will understand what are Static Variables in C++ Programming and how to create them along with some examples.

What are Static Variables in C++?

When we declare a variable with the static keyword, it is called Static Variable. It can be declared in a class or a function.

Static Variable in a Class

When a static variable is declared in a class, it is shared between all the objects of that class. We can access a static variable by class name using the scope resolution operator or by the object of the class using a dot (.) operator.

Each object does not have a separate copy of static variable so it can't be initialized using a constructor. They are initialized outside the class using the class name and scope resolution operator.

video-poster

Example

#include <iostream>

using namespace std;

class data
{
    // creating instance variables
  public:
    static int x;
};

// Initialized static variable using class name and scope resolution operator
int data::x=10;

int main()
{
    // Creating an object a and b of the class data
    data a;
    data b;

    // Access the values of static variable using object a and b
    cout<<"a.x="<<a.x<<endl;
    cout<<"b.x="<<b.x<<endl<<endl;

    // Change the values of static variable using object a
    a.x=20;
    cout<<"a.x="<<a.x<<endl;
    cout<<"b.x="<<b.x<<endl<<endl;

    // Change the values of static variable using class name
    data::x=30;
    cout<<"a.x="<<a.x<<endl;
    cout<<"b.x="<<b.x<<endl;

    return 0;
}

Output

a.x=10
b.x=10

a.x=20
b.x=20

a.x=30
b.x=30

Static Variable in a Function

When a static variable is declared in a function, and we store a value in it during the first function call, the value in it does not get erased even after the execution of the function is over. The value is carried to the next function call.

The memory for the static variable is allocated only once and is destroyed only when the main program ends execution; that's why it can hold its last stored value even after the execution of the function call is over.

Example

#include <iostream>

using namespace std;

void calculate()
{
    static int x=0;
    x=x+1;
    cout<<"x="<<x<<endl;
}

int main()
{
    // first time function call
    calculate();

    // second time function call
    calculate();

    return 0;
}

Output

x=1
x=2

In the above example, when we call the calculate() function for the first time, then the static variable x gets initialized by 0. Then it is incremented by 1, so the final value of x becomes 1 and is displayed on the output screen.

In the second call, the static variable x is not initialized by 0. Instead, it carried its last value of 1, and it incremented again by 1, and this time the final value of x becomes 2 and is displayed on the output screen.