局部变量
#include "stdio.h"
int myadd(){
int x = 0;
static int y = 0;
x= x +1;
y = y+1; // 一直累积
printf("x=%d , y=%d \n",x,y);
}
测试
int main(){
myadd();
myadd();
myadd();
myadd();
myadd();
return 1;
}
输出
观察y的值
x=1 , y=1
x=1 , y=2
x=1 , y=3
x=1 , y=4
x=1 , y=5
static修饰的函数
static int myaddstatic(){
return 1;
}
静态函数的作用域仅限于当前文件,不能被其它文件调用,
这个和java有点不同,java只要是公开的静态函数,就可以被其他文件所访问
C语言是没用static修饰的函数,反而可以被其他文件所访问,用static修饰的函数,反而不能被其他文件访问
static修饰变量
a文件定义
static int PAGE_SIZE = 20;
b文件
extern int PAGE_SIZE;
b文件是使用不了PAGE_SIZE的
如果使用,编译的时候,就会报错
CMakeFiles\cdemo.dir/objects.a(mystat1.c.obj):mystat1.c:(.rdata$.refptr.PAGE_SIZE[.refptr.PAGE_SIZE]+0x0): undefined reference to `PAGE_SIZE’
总结
java用static修饰是全局,给其他文件使用的
c用static修饰的全局变量和函数,反而禁止了其他文件的使用