Lifetime of a Static Variable in a C++ Function



The lifetime of a static variable in a C++ function exists till the program executes. We can say the lifetime of a static variable is the lifetime of the program. The static variable is a variable that is declared using the static keyword. The space for the static variable is allocated only one time, and this is used for the entirety of the program.

In this article, we will understand the lifetime of the static variable and the reason behind its lifetime.

Why do Static Variable Exists until program execution?

A static variable is initialized only once when the function is called for the first time. When we use the local variables, they get reinitialized after each function call, but the static variable maintains its value between function calls. It regains the last value for future function calls. The static variable remains in memory until the program gets executed or completed. The static variable is not destroyed on the function completion.

Example 1

In this example, we record the count of the function being called. In the function func(), we have used the static variable to store the count, whereas in the function function(), we have used a normal integer variable.

The static variable does not get reinitialized after each call and keeps the count of function calls, while the integer variable reinitializes to its initial value.

#include <iostream>
using namespace std;
// With static 
void func()
{
   static int num = 1;
   cout << "Value of num: " << num << "\n";
   num++;
    
}
// Without static 
void function()
{
   int number = 1;
   cout << "Value of number: " << number << "\n";
   number++;
    
}

int main()
{
   func();
   func();
   func();
   function();
   function();
   function();
   return 0;
}

The output of the above code is as follows:

Value of num: 1
Value of num: 2
Value of num: 3
Value of number: 1
Value of number: 1
Value of number: 1

Example 2

The following example returns the number of times the function is called using the static variable:

#include <iostream>
using namespace std;

void func(int n)
{
   static int counter = 0;
   counter++;

   if (n == 0)
   {
      cout << "Total calls made: " << counter << "\n";
      return;
   }

   func(n - 1);
}

int main()
{
   func(5);
   return 0;
}

The output of the above code is as follows:

Total calls made: 6
Updated on: 2025-05-15T19:33:43+05:30

17K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements