目录
1. 常见关键字
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
auto是自动的 - 每个局部变量都是auto修饰的(可省略,默认省略)
int main()
{
//int char;
{
int a=10;//自动创建,自动销毁 - 自动变量
//auto 省略掉了
//auto 新的C语言语法中也有其他用法 - 暂时不考虑
}
return 0;
}
extern 是用来申明外部符号的
register 寄存器关键字,其创建的变量建议放入寄存器中
int main()
{
//大量/频繁被使用的数据,想放在寄存器中,提升效率
register int num = 100;//建议num的值存放在寄存器中
return 0;
}
计算机中的数据可以存储到哪里呢?
signed 有符号的 10 -20
unsigned 无符号的
static 静态的!
union 联合体(共用体)
void 无 - 空
volatile C语言中暂时不讲
define - 不是关键字,是预处理指令
include - 不是关键字,是预处理指令
1.1 关键字 typedef
typedef 顾名思义是类型定义(类型重定义),这里应该理解为类型重命名。
比如:
unsigned int 无符号整型
// 将 unsigned int 类型 重命名为 uint_32, 所以 uint_32 也是一个类型名,是一样的typedef unsigned int uint_32 ;int main (){// 观察 num1 和 num2, 这两个变量的类型是一样的unsigned int num1 = 0 ;uint_32 num2 = 0 ;return 0 ;}
1.2 关键字static
在C语言中:
static是用来修饰变量和函数的
1. 修饰局部变量-称为静态局部变量
2. 修饰全局变量-称为静态全局变量
3. 修饰函数-称为静态函数
1.2.1 修饰局部变量
//代码1
#include <stdio.h>
void test()
{
int i = 0;
i++;
printf("%d ", i);
}
int main()
{
int i = 0;
for (i = 0; i < 10; i++)
{
test();
}
return 0;
}
运行结果:
//代码2
#include <stdio.h>
void test()
{
//static修饰局部变量
static int i = 0;
i++;
printf("%d ", i);
}
int main()
{
int i = 0;
for (i = 0; i < 10; i++)
{
test();
}
return 0;
}
运行结果:
对比代码1和代码2的效果理解static修饰局部变量的意义。
#include<stdio.h>
void test()
{
int a = 1;
a++; //局部变量a,作用域范围在test函数内,出了这个域就被销毁了,所以打印结果10个2
printf("%d ", a); //打印10个2
}
int main()
{
int i = 0;
while(i<10)
{
test();
i++;
}
return 0;
}
运行结果:
#include<stdio.h>
void test()
{
static int a = 1;//static代替auto修饰的int a,auto表示自动创建和销毁,那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++;//a++起作用 2 3 4 5 6 7 8 9 10 11
}
return 0;
}
结论:
static修饰局部变量改变了变量的生命周期(本质上是改变了变量的存储类型)。static代替auto修饰的int a,auto表示自动创建和销毁,那static应该表示只执行一次创建过程。静态局部变量在编译时候赋予初值,每次调用函数不在重新赋初值,函数结束不销毁。
本质上由栈区改变到了静态区
内存上划分为的区域见上↑
让静态局部变量出了作用域依然存在,到程序结束,生命周期才结束。
1.2.2 修饰全局变量
//代码1
//add.c
int g_val = 2018;
//test.c
int main()
{
printf("%d\n", g_val);
return 0;
}
//代码2
//add.c
static int g_val = 2018;
//test.c
int main()
{
printf("%d\n", g_val);
return 0;
}
解决方法;
如果添加个static后
原因:
static 修饰全局变量,使得这个全局变量只能在自己所在的源文件(.c)内部使用,其他源文件不能使用!
全局变量,在其他源文件内部可以被使用,是因为全局变量具有外部链接属性。但是被static修饰后,就变成了内部链接属性,其他源文件就不能链接到这个静态的全局变量了!
1.2.3 修饰函数
//代码1
//add.c
int Add(int x, int y)
{
return c+y;
}
//test.c
int main()
{
printf("%d\n", Add(2, 3));
return 0;
}
//代码2
//add.c
static int Add(int x, int y)
{
return c+y;
}
//test.c
int main()
{
printf("%d\n", Add(2, 3));
return 0;
}
运行结果:
添加static后:
原因:
static修饰函数,使得函数只能在自己所在的源文件内部使用,不能在其他源文件内部使用。
本质上:static是将函数的外部链接属性变成了内部链接属性!(与static修饰全局变量一样!)