您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

静态变量在C/C++中存储在哪里?

2024/2/21 5:47:25发布20次查看
静态变量是程序运行时保留在内存中的变量,即它们的生命周期是整个程序运行的时间。这与自动变量不同,它们仅在函数运行时保留在内存中,并在函数结束时被销毁。
静态变量存储在内存的数据段中。数据段是程序虚拟地址空间的一部分。
所有没有显式初始化或初始化为零的静态变量都存储在未初始化数据段(也称为未初始化数据段)中。 bss 段)。与此相比,初始化的静态变量存储在初始化的数据段中。
示例如下 -
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.
演示 c 语言静态变量的程序如下 -
示例 现场演示
#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;}
上述程序的输出如下 -
5678910
现在让我们理解上面的程序。
在函数func()中,i是一个静态变量,被初始化为4。因此它存储在初始化数据段中。然后 i 递增并返回其值。显示这一点的代码片段如下 -
int func(){ static int i = 4 ; i++; return i;}
在函数main()中,函数func()被调用6次,它返回打印的i的值。由于 i 是静态变量,因此在程序运行时它会保留在内存中并提供一致的值。显示这一点的代码片段如下 -
printf("%d\n", func());printf("%d\n", func());printf("%d\n", func());printf("%d\n", func());printf("%d\n", func());printf("%d\n", func());
以上就是静态变量在c/c++中存储在哪里?的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product