Where are static variables stored in C/C++?


Static variables 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.

The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program.

All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment). Compared to this, the static variables that are initialized are stored in the initialized data segment.

An example of this is given as follows −

static int x = 5;
static int y;

The static variable x is stored in the initialized data segment and the static variable y is stored in the BSS segment.

A program that demonstrates static variables in C is given as follows −

Example

 Live Demo

#include<stdio.h>
int func(){
   static int i = 4 ;
   i++;
   return i;
}

int main(){
   printf("%d\n", func());
   printf("%d\n", func());
   printf("%d\n", func());
   printf("%d\n", func());
   printf("%d\n", func());
   printf("%d\n", func());

   return 0;
}

The output of the above program is as follows −

5
6
7
8
9
10

Now let us understand the above program.

In the function func(), i is a static variable that is initialized to 4. So it is stored in the initialized data segment. Then i is incremented and its value is returned. The code snippet that shows this is as follows −

int func(){
   static int i = 4 ;
   i++;
   return i;
}

In the function main(), the function func() is called 6 times and it returns the value of i which is printed. Since i 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 −

printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements