
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Example
A program that demonstrates a static variable is given as follows.
#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
Explanation
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; }