关键字:static 和#define 定义常量和宏

98 阅读1分钟

常见关键字

image.png static 1.修饰局部变量 2.修饰全局变量 3.修饰函数
1. 修饰局部变量

#include <stdio.h>
void test()
{
	int a = 1;
	a++;
	printf("%d\n", a);
}

int main()
{
	int i = 0;
	while (i < 10)
	{
		test();
		i++;
	}
	system("pause");
	return 0;
}

image.png

#include <stdio.h>
void test()
{
	static int a = 1;
	a++;
	printf("%d\n", a);
}
int main()
{
	int i = 0;
	while (i < 10)
	{
		test();
		i++;
	}
	system("pause");
	return 0;
}

image.png Static 修饰局部变量,改变了局部变量的生命周期(本质上是改变了变量的存储类型)

image.png

2.修饰全局变量

image.png

image.png

image.png

image.png

image.png

define定义标识符常量和宏

#include <stdio.h>
//define定义标识符常量
#define MAX 100;
//define定义宏
#define ADD(x,y) ((x)+(y))//结果是20
#define ADD(x,y)  x+y//结果是11   4*2+3
int main()
{
	int  sum = ADD(2, 3);
	printf("sum =%d\n", sum);
	sum = 4 * ADD(2, 3);
	printf("sum=%d\n", sum);
	system("pause");
	return 0;
}

image.png