c语言static关键字的理解和使用


>>返回总目录<<

1 static的作用

在c语言中,全局变量或者函数是全局可访问的,对整个程序的各个部分而言都可见,static可以将其作用域限定为声明处至源文件末尾,以达到隐藏外部对象的目的。以static修饰的函数或变量会保存在静态存储区。static可以修饰全局变量,函数和局部变量。

2 static的用法示例

2.1 static修饰全局变量

在File.c中定义一个静态全局变量,在File2.c中调用时会报错。

File1.c
	#include "stdafx.h"
	/* 用static定义全局变量 */
	static int FileNumber = 100;
	
File2.c
	#include "stdafx.h"
	#include <stdlib.h>
	
	extern int FileNumber;/* 声明别处定义的static变量会报错 */
	int _tmain(int argc, _TCHAR* argv[])
	{
		printf("FileNumber: %d\n", FileNumber);
		return 0;	
	}
	
Error:
	error LNK2001: unresolved external symbol "int FileNumber" (?FileNumber@@3HA)

2.2 static修饰局部变量

局部变量是存放在栈中的,随着所在函数的调用和退出而存在和消失。

void OutputFun()
{
    int i = 0;
    i++;
    printf("%d ", i);
}
int main()
{
    int j = 0;
    for(j = 0; j < 5; j++)
    {
        OutputFun();
    }
    return 0;
}

Output: 1 1 1 1 1 

static类型的局部变量,称为局部静态变量,其值不会随函数退出而清除,生命周期依然存在,当函数再次调用时,它的值是上一次调用结束后的值。换句话说,static是一种只能在某个特定函数中使用但一直占据存储空间的变量。

void OutputFun()
{
    static int i = 0;
    i++;
    printf("%d ", i);
}
int main()
{
    int j = 0;
    for(j = 0; j < 5; j++)
    {
        OutputFun();
    }
    return 0;
}

Output: 1 2 3 4 5 

2.3 static修饰函数

静态函数的作用域只限于本文件,不能被其他文件调用,否则会报编译错误。

File1.c
	#include "File1.h"
	#include "stdafx.h"
	
	static void FileOutput()
	{
		printf("File1 Output!\n");
	}
	
File2.c
	#include "stdafx.h"
	#include <stdlib.h>
	
	extern void FileOutput();
	int main(int argc, _TCHAR* argv[])
	{
		FileOutput();
		return 0;	
	}
	
Error:
	error LNK2001: unresolved external symbol "void FileOutput()" (?FileNumber@@3HA)
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

woniudaidai

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值