C语言-static关键词,寄存器变量,define宏定义

static

static修饰局部变量

复制代码
#include<stdio.h>


//static修饰局部变量
void test() {
	//int a = 1;
	//a++;
	//printf("%d ", a); //输出: 2 2 2 2 2 2 2 2 2 2 

	static int a = 1;  //static修饰局部变量的时候,局部变量出了作用域,不销毁的;本质上,static修饰局部变量的时候,改变了变量的存储位置
	a++;
	printf("%d ", a); //输出: 2 3 4 5 6 7 8 9 10 11
}
int main() {
	int i = 0;
	while (i<10) {
		test();
		i++;
	}
	return 0;
}

static修饰全局变量

复制代码
创建一个add.c文件,内容如下:
//全局变量
static int g_val = 2026;

//全局函数
static int Add(int x, int y) {
	return x + y;
}



//创建一个main.c文件,内容如下

#include<stdio.h>

//static修饰全局变量(全局变量的外部链接属性就变成了内部连接属性,其他源文件(.c)就不能在使用这个全局变量)
//声明外部符号
extern int g_val;

int main(){
	printf("%d\n",g_val);
}

static修饰函数

复制代码
创建一个add.c文件,内容如下:
//全局变量
static int g_val = 2026;

//全局函数
static int Add(int x, int y) {
	return x + y;
}

#include<stdio.h>

//static修饰函数(全局函数的外部链接属性就变成了内部连接属性,其他源文件(.c)就不能在使用这个全局变量)
extern int Add(int x, int  y);

int main() {
	int a=10;
	int b = 20;
	int z = Add(a,b);
	printf("%d\n", z);
}

寄存器变量

复制代码
#include<stdio.h>
//寄存器变量
int main() {
	register int num = 3;//建议: 3 存放在寄存中
	return 0;
}

define宏定义

复制代码
#include<stdio.h>
//define定义标识符常量
#define NUM = 100;

//define定义宏
//宏是有参数的
#define ADD(x,y) x+y
int main() {
	int a = 10;
	int b = 20;
	int c = ADD(a,b);
	printf("%d\n", c);
}
相关推荐
晓蛋1 天前
c语言指的是什么意思
c语言·编译器·编程开发·集成开发环境·程序实例
小羊没烦恼!1 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
傲世仙尊1 天前
目录即文件-Ext文件系统收尾篇
linux·c语言
牵猫散步的鱼儿1 天前
重载、重写(覆盖)、重定义区别
c语言
伞伞悦读1 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
phltxy1 天前
C 语言指针:从内存地址到灵活的数据访问
c语言
C语言小火车1 天前
C/C++ 为什么需要编译器?
开发语言·c++
phltxy1 天前
C 语言中的数据存储:从类型到二进制位
c语言
霍霍的袁1 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
孙启超1 天前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust