static修饰的函数或者变量存在两种情况: 第一, 全局的静态函数和方法; 第二, 局部的静态变量。
第一: 全局的static变量和方法
全局的Static变量和函数,仅仅在定义的文件中有效。
<!--[if mso & !supportInlineShapes & supportFields]><span lang=EN-US><v:shape id="_x0000_i1025" type="#_x0000_t75" style='width:5in; height:195pt'> <v:imagedata croptop="-65520f" cropbottom="65520f" /> </v:shape><span style="mso-element:field-end" mce_style="mso-element:field-end"></span></span><![endif]-->
存在以下两个文件:
第一个文件是头文件: //definestatic.h #ifndef DEFINESTATIC_H_ #define DEFINESTATIC_H_ static int name = 10; #endif /* DEFINESTATIC_H_ */ 第二个文件是源文件: //MyTest.c #include <stdio.h> #include "definestatic.h" int main() { name = name + 10; printf("this is the variable value %d /n", name); printf("this is the return value %d /n", function());
然后再定义两个文件,都含有相同的名称为function的静态和非静态函数,
如下面的源代码所示:
//staticFunction.c static int function() { return 0; } 第二个文件: //nostaticFunction.c #include "definestatic.h" int function() { name = name + 100; return name; }
<!--[if mso & !supportInlineShapes & supportFields]><span lang=EN-US><v:shape id="_x0000_i1027" type="#_x0000_t75" style='width:5in; height:257.4pt'> <v:imagedata croptop="-65520f" cropbottom="65520f" /> </v:shape><span style="mso-element:field-end" mce_style="mso-element:field-end"></span></span><![endif]-->
结果:
this is the variable value 20
this is the return value 110
表明:
1. static定义的函数,或者变量,仅仅在文件域有效。所谓的文件域,就是包含头文件在内的文件域。
2.基于第一点,static 变量不会和其它文件域中的static变量冲突
3. 同一个文件,不能同时出现static和非static变量。
static函数用途非常广,因为c语言中全局的函数不宜太多,因此,用static方法可以限制函数的可见性
第二: 局部的静态变量【不提及局部方法, 因为暂时用得不多】
局部的静态变量, 局部的静态变量具有局部的全局性。即某个函数的局部静态变量,对这个函数是可见的。并且只初始化一次。
【注意,局部并不一定是函数中的局部,而是一个区块中的局部】
看如下代码:
#include <stdio.h> int test(int type) { int a = -1; if (type == 1) { static int s = 100; s = s + 5; a = s; } else { static int s = 1000; s = s + 5; a = s; } return a; } int main(void) { int result1 = test(1); printf("result1: %d/n",result1); int result2 = test(0); printf("result2: %d/n",result2); int result3 = test(1); printf("result3: %d/n",result3); int result4 = test(0); printf("result3: %d/n",result4); return 0; }
结果:
result1: 105
result2: 1005
result3: 110
result3: 1010
这里充分展示了static变量对于某个区块的全局可见性,并且不进行第二次初始化。
可能大家注意到,在全局的static中,没有两次初始化问题,原因是全局域无法出现两次调用的情形。因为全局域永远只
经历一次。如果经历多次,类似于头文件重复包含,将出现重复定义的问题。
另外,全局域不允许出现函数调用,或者参数赋值这类逻辑操作。