Summary: In this tutorial, we will discuss with the example what is a static variable in C++, how to declare, and when to use a static variable in our program.

What is Static Variable?

A variable, when declared following the ‘static‘ keyword, becomes a static variable.

Syntax:

If a static variable is declared:

  • Inside a class then all the instance of the class (i.e. object) shares the same copy of the variable. Also the variable can be accessed directly with class name.
  • Inside a function then its value is preserved between successive calls to that function for the lifetime (program) but cannot be accessible outside the scope or function in which it has been declared.

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

Example 1: Static Variable inside of a Class

Output:

Notice, we have created an object of Natural class and used incerase() method to increment the value of num two times and then again we created another object of the same class but this time we didn’t call the incerase() method but output the value of num.

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

Example 2: Static Variable inside a Function

Output

Notice the output in this case. We have called the increase function in the main two times and on the second call, the output is the incremented value of the initial 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 rest of the successive function calls use the same copy.

When to use Static Variable in C++?

  • When you want to use old value of variable (last function call) into the current function call. (like Example 2)
  • When you want to share same copy of the variable in class among all its objects.

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

Leave a Reply