Home  >  Article  >  Backend Development  >  Where are static variables stored in C/C++?

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

王林
王林forward
2023-09-15 21:09:031249browse

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

#Static variables are variables that remain in memory while the program is running, that is, their life cycle is the time the entire program is running. This is unlike automatic variables, which only remain in memory while the function is running and are destroyed when the function ends.

Static variables are stored in the data segment of memory. The data segment is part of the program's virtual address space.

All static variables that are not explicitly initialized or initialized to zero are stored in the uninitialized data segment (also called the uninitialized data segment). BSS segment). In contrast, initialized static variables are stored in the initialized data segment.

The example is 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.

The program that demonstrates C language static variables is as follows-

Example

Live demonstration

#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 above program The output 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 initialized to 4. Therefore it is stored in the initialization data segment. Then i is incremented and its value is returned. The code snippet showing 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 printed. Since i is a static variable, it remains in memory and provides a consistent value while the program is running. A code snippet showing 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());

The above is the detailed content of Where are static variables stored in C/C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete