Static variables in C++

We will understand static variables along with its applications and use cases in C++ using examples in this article.

What is a Static Variable?

A var becomes a static variable if the static keyword was used before its definition.

Syntax

static <type> <variable_name>;

The place where a static keyword is specified determines the purpose for which it is used. If a variable is defined within a class, all class instances—that is, all objects—will have the same version of the variables, and we may access it outside of the class without requiring any objects by calling it by its class name. Its value is maintained between calls if it is declared inside of a function for the duration of the programme, but it cannot be accessed outside of the function or scope in which it is defined. Let's look at some C++ examples of both categories of static variables.

Code

#include <iostream>
using namespace std;

class Natural{
public:
    static int num;

    void increase(){
        ++num;
    }
};
/*    It's crucial to initialize the static variable outside of a class, and we accomplish this by combining the class name with the 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


Even though we haven't increased the num of the second object, the result shows that the values of num for both objects are the same. The fact that num has the same value in both objects shows that a static variable is shared by both of them.

Static Variable inside a Function

Code

#include <iostream>
using namespace std;

void increase(){
    static int num = 0;
    cout << ++num << endl;
}

int main(){
    increase();
    increase();
    return 0;
}
 


Output:

1

2

Watch the result in this scenario. In the main method, the increase() function has been called twice, with the second call returning the first call's increased value. This demonstrates that a static variable inside a function is only defined once during the initial function call, and all subsequent calls to the same function utilize the same copy.

All of the objects in a class share a static variable with it. A static variable included within a function or scope stays in memory for the duration of the programme.

Static Variable Uses

When we wish to reuse a variable's altered value from one function call to the next, we should utilize a static variable. Or if we want the class variable to remain constant across all objects. In this course, we learnt what a static variable in C++ is, how important it is, and when to utilize one.