What is the lifetime of a static variable in a C++ function?


A static variable is a variable that is declared using the keyword static. The space for the static variable is allocated only one time and this is used for the entirety of the program.

Once this variable is declared, it exists till the program executes. So, the lifetime of a static variable is the lifetime of the program.

A program that demonstrates a static variable is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
void func() {
   static int num = 1;
   cout <<"Value of num: "<< num <<"\n";
   num++;
}
int main() {
   func();
   func();
   func();
   return 0;
}

Output

The output of the above program is as follows.

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

Now, let us understand the above program.

In the function func(), num is a static variable that is initialized only once. Then the value of num is displayed and num is incremented by one. The code snippet for this is given as follows −

void func() {
   static int num = 1;
   cout <<"Value of num: "<< num <<"\n";
   num++;
}

In the function main(), the function func() is called 3 times. The value num is allocated only once and not on every function call. The code snippet for this is given as follows.

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

Updated on: 26-Jun-2020

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements