9-一些关键字
一.static关键字
1.static修饰局部变量
#include<stdio.h>void test()
{int i = 1; // i是局部变量,生命周期在test函数内部i++;printf("%d ", i);
}int main()
{int i = 0;while (i < 10){test(); // 执行完后,test函数内部的局部变量i就被销毁了,下次再调用test函数时里面的i会被重新赋值为1i++;}return 0;
}
输出:
2 2 2 2 2 2 2 2 2 2
#include<stdio.h>void test()
{static int i = 1; // static修饰局部变量时,局部变量出了它的作用域不会被销毁。本质上这时改变了变量的存储位置// 内存分为栈区、堆区和静态区;栈区用于存放局部变量,若一个局部变量被static修饰,则这个局部变量变为静态变量,会被放在静态区// 静态区的变量只有当程序销毁程序结束后才会被销毁(生命周期变长,与程序的生命周期一样)i++;printf("%d ", i);
}int main()
{int i = 0;while (i < 10){test();i++;}return 0;
}
输出:
2 3 4 5 6 7 8 9 10 11
分析:使用static修饰局部变量,局部变量变为静态变量,存放这个变量的内存区从栈区转到静态区,而静态区的变量生命周期是整个程序的生命周期。所以当程序在运行时,test内部的变量i也一直存在,而不会被销毁从而重新被赋值为1
2.static修饰全局变量
在源文件中有两个这样的文件:static_demo2.c static_demo2_test.c
static_demo2.c内容:
#include<stdio.h>int g_val = 10; // 全局变量
static_demo2_test.c内容:
#include<stdio.h>extern int g_val; // extern关键字用于声明外部符号
int main()
{printf("%d\n", g_val);return 0;
}
运行程序,输出:
10
extern:外来的,外部的;这个关键字用与声明外部符号,即声明另外.c文件中的全局变量
在static_demo2.c中,g_val为全局变量,而全局变量具有外部链接属性,可以被外部文件所使用
在static_demo2.c中,改为:
#include<stdio.h>static int g_val = 10; // 全局变量
// static修饰全局变量时,全局变量的外部链接属性就变成了內部链接属性,其他源文件(.c文件)就不能使用这个全局变量了
再运行程序会报错:
无法解析的外部符号 g_val
3.static修饰函数
static_demo3.c源文件中:
#include<stdio.h>int main()
{int a = 10;int b = 20;int z = Add(a, b);printf("%d\n", z);
}
static_demo3_test.c源文件中:
int Add(int x, int y)
{return x + y;
}
运行程序,输出:
30
但是会有警告:
warning C4013: “Add”未定义;假设外部返回 int
但依然可以运行成功,这是因为函数也具有外部链接性。可以在static_demo3.c文件中修改代码为extern int Add(int x,int y);表示声明了外部这个函数,就不会有警告了
若static_demo3_test.c源文件修改为:
static int Add(int x, int y)
{return x + y;
}
运行则报错,使用static修饰后Add函数不再具有外部链接属性了
二.register寄存器关键字
register:登记,注册,(计算机)寄存器
电脑上的存储设备:
- 寄存器(集成到CPU上了)
- 高速缓存(cache)
- 内存
- 硬盘
四个设备从上往下:访问速度从快到慢,空间变大,造价变低
#include<stdio.h>int mainn()
{register int num = 3;//建议3放在寄存器中,读取速度更快;仅仅是建议,最终存放与否由编译器决定return 0;
}
三.define(注意define不是关键字!!!是预处理指令)
小贴士:在C或C++中,以#号开头的代码是预处理指令,它们在编译过程开始之前由预处理器处理
#include<stdio.h>#define NUM 100 // define关键字定义常量 且通常常量要用大写字母定义,与变量区别开来
#define ADD(x,y) ((x)+(y)) // define还可以定义宏,宏是有参数的。作用:定义名称替换规则,在编译前进行文本替换
int main()
{printf("%d\n", NUM);int b = 1, c = 2;int a = ADD(b, c);printf("%d\n", a);return 0;
}
四.typedef关键字
#include<stdio.h>// typedef数据类型重命名,相当于python中的astypedef unsigned int unit;
int main()
{unsigned int num1 = 0;unit num2 = 1;printf("%zu\n", sizeof(num1));printf("%zu\n", sizeof(num2));return 0;
}
输出:
4
4