C语言难点专题——static

本文详细解析了C语言中全局的静态变量和方法的使用方式及作用,包括其仅在定义文件内有效的特性,以及不会与其他文件域中的静态变量冲突的特点。同时,也介绍了局部静态变量的作用,即在特定函数内的全局可见性,且只初始化一次的特性。通过实例代码演示了这些概念的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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中,没有两次初始化问题,原因是全局域无法出现两次调用的情形。因为全局域永远只

经历一次。如果经历多次,类似于头文件重复包含,将出现重复定义的问题。


另外,全局域不允许出现函数调用,或者参数赋值这类逻辑操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值