static 修饰符—生命的魔法棒
普通的局部变量static修饰局部变量static修饰全局变量,守卫我的变量
static
英 [ˈstætɪk] 美 [ˈstætɪk]
adj. 静止的;静态的;停滞的;静力的
n. 天电(干扰);静电;静力学
就像它的本意,static作为C语言关键字,主要的作用就是冻结局部变量。局部变量在函数完成使命消亡后,继续存在,延长生命周期,下次继续调用。
普通的局部变量
void static_test
(int time
)
{
int num
= 0;
printf("%d time num value:%d\n",time
,num
);
num
++;
}
int main(int argc
, char const* argv
[])
{
static_test(1);
static_test(2);
static_test(3);
static_test(4);
static_test(5);
return 0;
}
1 time num value
:0
2 time num value
:0
3 time num value
:0
4 time num value
:0
5 time num value
:0
可以看出static_test函数中局部变量num的值,没有发生变化。num的值随着static_test函数的结束一起陪葬(消亡)了。下一次调用static_test函数的时候,再重新给变量num分配空间。所以每次调用static_test函数,num都是新生的变量,值都是0。
static修饰局部变量
void static_test
(int time
)
{
static int num
= 0;
printf("%d time num value:%d\n",time
,num
);
num
++;
}
int main(int argc
, char const* argv
[])
{
static_test(1);
static_test(2);
static_test(3);
static_test(4);
static_test(5);
return 0;
}
1 time num value
:0
2 time num value
:1
3 time num value
:2
4 time num value
:3
5 time num value
:4
可以看出num的值随着static_test函数的调用,依次递增。static关键字延长了num的生命,不会随着函数的结束而陪葬。只定义初始化一次,后面再次调用static_test函数时,会直接使用。但num的作用域没有变化,依旧只能在static_test函数内使用,否则产生报错。
int main(int argc
, char const* argv
[])
{
printf("the num value:%d",num
);
return 0;
}
hello
.c
:9:31: error
: use of undeclared identifier
'num'
printf("the num value:%d",num
);
^
1 error generated
.
static修饰全局变量,守卫我的变量
#ifndef _test_h
#define _test_h
void test_print(int a
);
#endif
#include<stdio.h>
static int a
= 12;
void test_print(int a
)
{
printf("this is main.c,the a value is :%d\n",a
);
}
#include <stdio.h>
#include "test.h"
int main(int argc
, char const* argv
[])
{
extern int a
;
printf("this is main.c,the a value is :%d\n",a
);
test_print(a
);
return 0;
}
Undefined symbols
for architecture x86_64
:
"_a", referenced from
:
_main in hello
-dcdf68
.o
ld
: symbol(s
) not found
for architecture x86_64
clang
: error
: linker command failed with exit code
1 (use
-v to see invocation
)
可以看出,经过static修饰的全局变量,只能在这个全局变量只能在所定义的文件内使用,其他文件不能使用。当test.c文件中去掉static关键字,就没有问题了。
this is main
.c
,the a value is
:12
this is test
.c
,the a value is
:12