C語言中的static
來源:程序員人生 發布時間:2015-06-15 08:03:22 閱讀次數:2868次
原理
C語言中的static可用來改變變量的作用域和生存期和函數的作用域,該關鍵字可以用來修飾函數的定義和聲明,和變量的定義。
用static修飾函數定義,表示該函數只在本文件有效(定義所在的文件),其它文件對該函數不可見。
用static修飾函數外的變量定義,表示該變量只在本文件有效(定義所在的文件),其它文件對該變量不可見。
用static修飾函數內的變量定義,表示該變量在屢次函數調用間1直有效。它的作用域依然是函數,但生存期是全部程序的生存期
用static修飾函數聲明,表示該函數的定義只能在本文件
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);
}
實驗結果

生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈