In this article, 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 ‘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 it in effect with examples.

Example 1: Static Variable inside of a Class

Output:

As you can notice that 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 outputted the value of num. The value of num in both object 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 main two times and on second call the output is the incremented value of the initial value of first increase() function call. This proves that the static variable inside a function is declared only once on first function call and rest of the successive function calls uses the same copy.

When to use Static Variable

  • 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.

Hope you got some idea about the static variable in C++.

Leave a Reply

Close Menu