

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
When do function-level static variables get initialized in C/C++?
Static variables can be defined using the static keyword. They are variables that remain in memory while the program is running i.e. their lifetime is the entire program run. This is different than automatic variables as they remain in memory only when their function is running and are destroyed when the function is over.
Function-level static variables are created and initialized the first time that they are used although the memory for then is allocated at program load time.
A program that demonstrates function-level static variables in C is given as follows −
Example
#include<stdio.h> int func() { static int num = 0; num += 5; return num; } int main() { for(int i = 0; i<5; i++) { printf("%d\n", func()); } return 0; }
Output
The output of the above program is as follows.
5 10 15 20 25
Now let us understand the above program.
The function func() contains a static variable num that is initialized to 0. Then num is increased by 5 and its value is returned. The code snippet that shows this is as follows.
int func() { static int num = 0; num += 5; return num; }
In the function main(), the function func() is called 5 times using a for loop and it returns the value of num which is printed. Since num is a static variable, it remains in the memory while the program is running and it provides consistent values. The code snippet that shows this is as follows.
int main() { for(int i = 0; i<5; i++) { printf("%d\n", func()); } return 0; }
- Related Questions & Answers
- Do static variables get initialized in a default constructor in java?
- When are static C++ class members initialized?
- Why are global and static variables initialized to their default values in C/C++?
- Static Variables in C
- Class and Static Variables in C#
- Initialization of static variables in C
- Templates and Static variables in C++
- How are C++ Local and Global variables initialized by default?
- Static variables in Java
- Default values of static variables in C
- Where are static variables stored in C/C++?
- C++ static member variables and their initialization
- When are static objects destroyed in C++?
- Final static variables in Java
- Initialization of global and static variables in C