11.常见关键字
C语言提供了丰富的关键字,这些关键字都是语言本身预先设定好的,用户自己是不能创造关键字的。
auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while
注:关键字,先介绍下面几个,后面遇到再展开
11.1关键字typedef
typedef 顾名思义是类型定义,这里应该理解为类型重命名。
比如:
#include<stdio.h>
struct Node
{
int date;
struct Node* next;
};
int main()
{
unsigned int num = 0;
struct Node n;
return 0;
}
可写成以下形式
#include<stdio.h>
typedef unsigned int uint;
typedef struct Node
{
int date;
struct Node* next;
}Node;
int main()
{
uint num = 0;
Node n;
return 0;
}
11.2关键字static
在C语言中:static是用来修饰变量和函数的
- 修饰局部变量–称为静态局部变量
- 修饰全局变量–称为静态全局变量
- 修饰函数–称为静态函数
11.2.1 修饰局部变量
代码1
#include <stdio.h>
void test()
{
int a = 1;
a++;
printf("%d\n", a);
}
int main()
{
int i = 0;
while (i < 10)
{
test();
i++;
}
return 0;
}
代码2
#include <stdio.h>
void test()
{
static int a = 1;
a++;
printf("%d\n", a);
}
int main()
{
int i = 0;
while (i < 10)
{
test();
i++;
}
return 0;
}
对比代码1和代码2理解static修饰局部变量的意义
结论:
static 修饰局部变量的时候,局部变量出了作用域,不销毁。本质上,static 修饰局部变量的时候,改变了变量的储存位置。影响了变量的生命周期,生命周期变长,和程序的生命周期一样。
11.2.2 修饰全局变量
代码1
add.c
int g_val = 100;
test.c
#include <stdio.h>
extern int g_val;//声明外部符号
int main()
{
printf("%d\n", g_val);
return 0;
}
代码2
add.c
static int g_val = 100;
test.c
#include <stdio.h>
extern int g_val;//声明外部符号
int main()
{
printf("%d\n", g_val);
return 0;
}
结论:
static 修饰全局变量的时候, 这个全局变量的外部链接属性就变成了内部链接属性, 使得这个全局变量只能在本源文件内使用, 其他源文件(.c)就不能再使用到这个全局变量了
11.2.3 修饰函数
代码1
add.c
int Add(int x, int y)
{
return x + y;
}
test.c
#include <stdio.h>
extern int Add(int x, int y);
int main()
{
int a = 10;
int b = 20;
int z = Add(a, b);
printf("%d\n", z);
return 0;
}
代码2
add.c
static int Add(int x, int y)
{
return x + y;
}
#include <stdio.h>
extern int Add(int x, int y);
int main()
{
int a = 10;
int b = 20;
int z = Add(a, b);
printf("%d\n", z);
return 0;
}
结论:
一个函数本来就是具有外部链接属性的,但是被static 修饰的时候,外部链接属性就变成了内部链接属性,其他源文件(.c)就无法使用了。
11.3关键字register
register为寄存器变量
#include <stdio.h>
int main()
{
register int num = 3;//register在这里的作用:建议3存放在寄存器中
return 0;
}