.
3ss.cn

C语言入门篇--关键字static详解

1.修饰局部变量

1.1作用

ststic修饰局部变量,会改变局部变量的生命周期,不改变作用域:

生命周期:和全局变量一样具有全局性,但在内存中的位置没有改变,还在在静态存储区中。

作用域:作用域不改变。

注意:静态局部变量的初始化在整个变量定义时只会进行一次。

1.2举例

(1)不加static

#include <stdio.h>
Show()
{
	int j = 0;
	j++;
	printf("j=%d\n", j);
}
int main()
{
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		Show();
	}
	return 0;
}

(2)加static

#include <stdio.h>
Show()
{
	static int j = 0;//生命周期变为全局的,
	j++;
	printf("j=%d\n", j);
}
int main()
{
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		Show();
	}
	return 0;
}

(3)静态局部变量的初始化只会进行一次

#include <stdio.h>Show()
{
	static int j = 0;
	j = 3;
	j++;
	printf("j=%d\n", j);
}int main()
{
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		Show();
	}
	return 0;
}

2.修饰全局变量

2.1作用

static修饰全局变量,表示全局变量只在本文件内有效,取消了全局变量的跨文件属性。

2.2举例

由于static对全局变量的作用在一个文件里体现不出来,固我们创建两个文件,
在test1.c中通过extern引用外部变量g_vale,在test2.c中创建全局变量g_vale 。

(1)不加static

test1.c:

#include <stdio.h>
extern int g_vale;
int main()
{
	printf("g_vale=%d\n", g_vale);
	return 0;
}

test2.c:

#include <stdio.h>
int g_vale = 100;//定义全局变量

编译运行:

(2)加static

test1.c

#include <stdio.h>
extern int g_vale;
int main()
{
	printf("g_vale=%d\n", g_vale);	return 0;
}

test2.c

#include <stdio.h>
static int g_vale = 100; //定义静态全局变量

编译运行:运行失败,无法解析外部符号g_vale

3.修饰函数

3.1作用

static修饰函数,和其修饰全局变量类似,表示函数只可在本文件内调用使用,取消了函数的跨文件属性。

3.2举例

由于static对函数的作用在一个文件里体现不出来,固我们创建两个文件,
在test1.c中通过extern引用外部函数Show( ),在test2.c中创建Show( )函数

(1)不加static

test1.c:

#include <stdio.h>
externShow();//也可以不写声明,文件在链接时也可以找到,但会出现Warning:Show()未定义
int main()
{
	Show();
	system("pause");
	return 0;
}

test2.c:

#include <stdio.h>
void Show()
{
	printf("This is Show()\n");
}

编译运行:

(2)加static

test1.c:

#include <stdio.h>
externShow();
int main()
{
	Show();
	system("pause");
	return 0;
}

test2.c:

#include <stdio.h>
static void Show()
{
	printf("This is Show()\n");
}

编译运行:运行失败,无法解析外部符号Show

赞(0)
未经允许不得转载:互联学术 » C语言入门篇--关键字static详解

评论 抢沙发