C語言中的static

原理

C語言中的static可用來改變變量的作用域和生存期以及函數的作用域,該關鍵字可以用來修飾函數的定義和聲明,以及變量的定義。

用static修飾函數定義,表示該函數只在本文件有效(定義所在的文件),其它文件對該函數不可見。

用static修飾函數外的變量定義,表示該變量只在本文件有效(定義所在的文件),其它文件對該變量不可見。

用static修飾函數內的變量定義,表示該變量在多次函數調用間一直有效。它的作用域仍然是函數,但生存期是整個程序的生存期


用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\n",a);

	a=2;
	printf("a=%d\n",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()\n");
}


void ff(void);
extern void print(void);



/***************************主函數***************************/
int main(){
	
	print();
	print();
	print();


	ff();

	
	printf("a=%d\n",a);
	f(); 

	return 0;
}


void print(void){
	static int n=0; 
	
	if(n==0)
	{
		printf("the first time\n");
		n=1;
	}
	else
	{
		printf("not the first time\n");
	}

	printf("the address of n is : %X\n",&n);
		
}

實驗結果



發佈了60 篇原創文章 · 獲贊 20 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章