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

王林
Release: 2023-09-15 21:09:03
forward
1228 people have browsed it

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.
Copy after login

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

Example

Live demonstration

#include 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; }
Copy after login

The above program The output is as follows -

5 6 7 8 9 10
Copy after login

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; }
Copy after login

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());
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!