Summary: In this tutorial, we will learn with examples the significance of the static variable in C++.

What is a Static Variable?

When the static keyword preceded the declaration of a variable, that variable becomes a static variable.

Syntax:

static <type> <variable_name>;

A static keyword serves a different purpose depending on where it has been declared.

If it is declared inside of a class, all instances of the class (i.e. objects) will share the same copy of the variable, and we can access it without any object by class name outside the class.

If it is declared inside of a function then its value is preserved between successive calls for the lifetime of the program, but it cannot be accessd outside the scope or function in which it is declared.

Let’s see examples of both types of static variables in C++.

Example 1: Static Variable inside of a Class

#include <iostream>
using namespace std;
 
class Natural{
public:
    static int num;
 
    void increase(){
        ++num;
    }
};
/* 
  *It is important to initialize the static variable outside of a class
  *we do so by using the class name and scope resolution operator.
*/
int Natural::num = 0;
 
int main()
{   
    //Creating 1st object
    Natural obj1;
 
    //Incrementing Natural::num 2 times
    obj1.increase();
    obj1.increase();
 
    cout << "Num of 1st Object: "<< obj1.num << endl;
 
    //Creating 2nd object
    Natural obj2;
 
    cout << "Num of 2nd Object: "<< obj2.num << endl;
 
    return 0;
}

Output:

Num of 1st Object: 2
Num of 2nd Object: 2

Observe the output, the value of num of both the objects are the same, regardless of the fact that we have not incremented the num of the second object.

The same value of num in both objects proves that a static variable is shared among the objects.

Example 2: Static Variable inside a Function

#include <iostream>
using namespace std;
 
void increase(){
    static int num = 0;
    cout << ++num << endl;
}
 
int main(){
    increase();
    increase();
    return 0;
}

Output:

1
2

Observe the output in this case. We have called the increase function twice in the main method and on the second call, the output is the incremented value of the first increase() function call.

This proves that the static variable inside a function is declared only once on the first function call and the remaining successive function calls use the same copy.

Conclusion

A static variable within a class is shared by all the objects of the class.

A static variable inside a scope or function remains in the memory for the lifetime of the program.

When to use Static Variable in C++?

We should use a static variable whenever we want to reuse the modified value of the variable inside a function in the next function call.

Or when we want all the objects to maintain a single copy of the class variable.

In this tutorial, we learned what a static variable is, what its significance is, and when we should use static variable in C++.

Leave a Reply