最近经常碰到static,之前也使用过,但都是一知半解,所以下决心做个整理总结,搞搞灵清它到底用哪些作用。

一.static in C

1.默认初始化为0:

  如果不显式地对静态变量进行初始化,它们将被初始化为0。

  static变量存放在Global/Static(全局区/静态区)。在静态数据区,内存中所有的字节默认值都是0x00,所以在程序一开始时static声明的变量会被默认初始化为0。

 

2.static声明的变量会一直保持其值(局部静态对象)

  static变量存放在Global/Static(全局区/静态区)。程序一开始,对其进行唯一一次初始化。被函数调用后,static变量不会消失,计算机会一直记录其值,其生命周期是贯穿函数调用及之后的时间。

 1 #include <stdio.h>
 2 void funcion();
 3 
 4 int main()
 5 {
 6     for(int count = 1; count <= 3; count++) {
 7         printf("第%d次调用:",count);
 8         funcion();
 9     }                    //for循环中的count内存被释放 
10     return 0;
11 } 
12 
13 void funcion() 
14 {
15     int temp = 10;
16     static int count = 10;//只在函数第一次调用时执行,后续函数调用此变量的初始值为上次调用后的值,每次调用后存储空间不释放
17     printf("temp = %d  static count = %d\n",temp--, count--);
18 }
Eg Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-13
  • 2022-12-23
  • 2021-06-10
  • 2021-08-22
  • 2022-01-24
  • 2021-12-08
相关资源
相似解决方案