关键字static和const

  • static

在C语言中static是用来修饰变量和函数的

1.修饰局部变量--->静态局部变量

//对比下面两个代码
#include <stdio.h>
void test()
{
	int i = 0;//i调用时生成,函数结束时释放
	i++;
	printf("%d\n", i);// 1 1 1 1 1 1 1 1 1 1
}
int main()
{
	for (int i = 0; i < 10; i++)
	{
		test();
	}
	system("pause");
	return 0;
}


#incldue <stdio.h>
//给局部变量加static关键字
void test()
{
	//static修饰局部变量改变了变量的生命周期,让静态局部变量出了作用域依然存在,到程序结束,生命周期才结束
	static int i = 0;//函数结束时不释放
	i++;
	printf("%d\n", i);//1 2 3 4 5 6 7 8 9 10
}
int main()
{
	for (int i = 0; i < 10; i++)
	{
		test();
	}
	system("pause");
	return 0;
}

局部变量在调用时生成,在函数结束时释放;static修饰的静态局部变量改变了变量的生命周期,让静态局部变量出了作用域依然存在,到程序结束,生命周期才结束。

静态局部变量只初始化一次,可以多次赋值。

2.修饰全局变量--->静态全局变量

一个全局变量被static修饰,使得这个全局变量只能在本源文件中使用,不能在其他源文件中使用。

//a.c
#include <stdio.h>
 int num = 717;
//b.c
int main()
{
	printf("%d\n", num);
	system("pause");
	return 0;
}



//a.c
#include <stdio.h>
static int num = 717;
//b.c
int main()
{
	printf("%d\n", num);
	system("pause");
	return 0;
}
//此代码在编译时会出现连接性错误

3.修饰函数--->静态函数

一个被static修饰的函数,使得这个函数只能在本源文件中使用,不能在其他源文件内使用。

//a.c
#include <stdio.h>
int Add(int x, int y)
{
	return x + y;
}
//b.c
#include <stdio.h>
int main()
{
	printf("%d\n", Add(1, 2));
	system("pause");
	return 0;
}

//a.c
#include <stdio.h>
//加static之后在编译时会出现连接性错误
static int Add(int x, int y)
{
	return x + y;
}
//b.c
#include <stdio.h>
int main()
{
	printf("%d\n", Add(1, 2));
	system("pause");
	return 0;
}
  • const

1.const修饰常变量

cosnt int i=717;

以上i被定义为一个只读常量,某种意义上它的值是不能被修改的,意义同常量一样,被存储在内存的全局变量区。

#include <stdio.h>
int main()
{
	const int i = 717;
	i++;//此时为报错,证明i不可以被修改
	printf("%d\n", i);
	system("pause");
	return 0;
}

但是在C语言中,可以使用指针修改其值

#include <stdio.h>
int main()
{
	const int i = 717;
	int *p = &i;
	//修改前的值
	printf("%d\n", i);
	//修改后的值
	*p = 12;
	printf("%d\n", i);
	system("pause");
	return 0;
}

2.const修饰指针变量

const如果放在*左边,其修饰的是指针指向的内容,保证指针指向的内容不能通过指针来改变。但是指针变量本身的内容可以改变。

const如果放在*右边,其修饰的是指针变量本身,保证指针变量的内容不能修改,但是指针指向的内容可以通过指针修改。

#include <stdio.h>
void test1()
{
	//cosnt 在*左边时修饰的是指针指向的内容,其不能进行修改,但指针变量本身的内容可以修改
	int i = 717;
	int j = 120;
	const int* p = &i;
	*p = 9;//会报错,不被允许
	p = &j;

}
void test2()
{
	//cosnt 在*右边时修饰的是指针变量本身,其内容不能进行修改,但指针指向的内容可以进行修改
	int i = 717;
	int j = 120;
	int *const p = &i;
	*p = 9;
	p = &j;//会报错,不被允许

	printf("%d %d", i, j);
}
int main()
{
	test1();
	test2();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43807876/article/details/114934453