When do function-level static variables get initialized in C/C++?

CC++Server Side Programming

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

 Live Demo

#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;
}
raja
Published on 22-Nov-2018 07:11:39
Advertisements