原理
C语言中的static可用来改变变量的作用域和生存期和函数的作用域,该关键字可以用来修饰函数的定义和声明,和变量的定义。
用static修饰函数定义,表示该函数只在本文件有效(定义所在的文件),其它文件对该函数不可见。
用static修饰函数外的变量定义,表示该变量只在本文件有效(定义所在的文件),其它文件对该变量不可见。
用static修饰函数内的变量定义,表示该变量在屡次函数调用间1直有效。它的作用域依然是函数,但生存期是全部程序的生存期
about声明和定义
如果定义先于使用,则不需要声明
当定义后于使用时,在使用之前声明
小实验
file1.cpp
#include<stdio.h>
//static variable,used only in a file
static int a;
//static function,used only in a file
static void f(void ){
a=1;
printf(a=%d
,a);
a=2;
printf(a=%d
,a);
}
void ff(void){
f();
}
main.cpp
#include<stdio.h>
//in f1.cpp,define a and f as static
int a;
void f(void){
printf(f()
);
}
void ff(void);
extern void print(void);
/***************************主函数***************************/
int main(){
print();
print();
print();
ff();
printf(a=%d
,a);
f();
return 0;
}
void print(void){
static int n=0;
if(n==0)
{
printf(the first time
);
n=1;
}
else
{
printf(not the first time
);
}
printf(the address of n is : %X
,&n);
}
实验结果