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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章