C存储类

基于菜鸟教程写的个人笔记

存储类

存储类定义了C程序中变量/函数的存储位置,生命周期,作用域

  1. auto
  2. register
  3. static
  4. extern

1.auto存储类

auto存储类是所有局部变量默认的存储类 定义在函数中的变量都默认为auto存储类 它们在函数开始时被创建,在函数结束时被销毁

1
2
3
4
{
	int month ;
	auto int month ;
}

auto只能修饰局部变量

2.register存储类

register存储类用于定义存储在寄存器上,而不是RAM中的局部变量 register存储类定义存储在寄存器,变量访问速度更快,不能直接地取地址(因为它存储在RAM中)

1
2
3
{
	register int miles 
}

寄存器一般用于需要快速访问的变量

3.static存储类

(1)static作用于局部变量

a.使局部变量在程序生命周期内都存在,不需要每次进入和离开其作用域(函数)的时候创建(重新分配内存)和销毁。 b.使用static修饰局部变量可以在函数调用之间保持局部变量的值

static作用的变量,静态局部变量存储在静态(全局)存储区

(2)static作用于全局变量

当static修饰全局变量时,会使变量的作用域限制在声明它的文件内

(3)静态变量的特性

静态变量在程序中只被初始化一次,即使函数被调用多次,该变量的值也不会重置

代码示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
 
/* 函数声明 */
void func1(void);
 
static int count=10;        /* 全局变量 - static 是默认的 */
 
int main()
{
  while (count--) {
      func1();
  }
  return 0;
}
 
void func1(void)
{
/* 'thingy' 是 'func1' 的局部变量 - 只初始化一次
 * 每次调用函数 'func1' 'thingy' 值不会被重置。
 */                
  static int thingy=5;
  thingy++;
  printf(" thingy 为 %d , count 为 %d\n", thingy, count);
}

实例中 count 作为全局变量可以在函数内使用,thingy 使用 static 修饰后,不会在每次调用时重置

当上面的代码被编译和执行时,它会产生下列结果:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
 thingy 为 6 , count 为 9
 thingy 为 7 , count 为 8
 thingy 为 8 , count 为 7
 thingy 为 9 , count 为 6
 thingy 为 10 , count 为 5
 thingy 为 11 , count 为 4
 thingy 为 12 , count 为 3
 thingy 为 13 , count 为 2
 thingy 为 14 , count 为 1
 thingy 为 15 , count 为 0

4.extern存储类

extern存储类用于定义在其他文件中声明的全局变量或函数 当使用extern关键字时,不会为变量分配任何存储空间,而只是指示编译器该变量在其他文件中定义

extern 存储类用于提供一个全局变量的引用,全局变量对所有的程序文件都是可见的。当您使用 extern 时,对于无法初始化的变量,会把变量名指向一个之前定义过的存储位置。

extern 修饰符通常用于当有两个或多个文件共享相同的全局变量或函数的时候,如下所示:

第一个文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <stdio.h>
 
int count ;
extern void write_extern();
 
int main()
{
   count = 5;
   write_extern();
}

第二个文件

1
2
3
4
5
6
7
8
#include <stdio.h>
 
extern int count;
 
void write_extern(void)
{
   printf("count is %d\n", count);
}

结果

在这里,第二个文件中的 extern 关键字用于声明已经在第一个文件 main.c 中定义的 count。现在 ,编译这两个文件,如下所示:

1
 $ gcc main.c support.c

这会产生 a.out 可执行程序,当程序被执行时,它会产生下列结果:

1
count is 5
experience
使用 Hugo 构建
主题 StackJimmy 设计