c存储类
存储类定义 C 程序中变量/函数的范围(可见性)和生命周期。这些说明符放置在它们所修饰的类型之前。下面列出 C 程序中可用的存储类:
auto //auto 只能修饰局部变量
register //
static //有static修饰时,调用函数时不会被重置
extern
#include<stdio.h>
#include<stdlib.h>
void func1(void); //函数声明
int count = 10; //全局变量
int main()
{
while(count--){
func1();
}
system("pause");
}
void func1(void){
static int thingy = 5; // 加上static,thingy每次调用时不会被重置
thingy++;
printf("thingy is %d, count is %d\n",thingy,count);
}
输出结果
thingy is 6, count is 9
thingy is 7, count is 8
thingy is 8, count is 7
thingy is 9, count is 6
thingy is 10, count is 5
thingy is 11, count is 4
thingy is 12, count is 3
thingy is 13, count is 2
thingy is 14, count is 1
thingy is 15, count is 0
extern 存储类用于提供一个全局变量的引用,全局变量对所有的程序文件都是可见的。
#include<stdio.h>
#include<stdlib.h>
#include"support.c"
int count;
extern void write_extern();
int main(){
count = 5;
write_extern();
system("pause");
}
#include<stdio.h>
extern int count;
void write_extern(){
printf("count is %d\n",count);
}
第二个文件中extern 关键字用于声明已经在第一个文件 main.c 中定义的 count,编译这两个文件,输出结果:count is 5