常见关键字
auto
int main()
{
auto int a = 10;//局部变量 - 自动变量
return 0;
}
//局部变量前边都有auto,为了方便我们一般都会省略
break
//停止循环
case
//switch case
char
//字符类型
const
//常变量用const修饰
continue
//应用在循环中
default
//默认 - 用在switch case 语句中
do
//do while 循环
double
//double类型
else
//if else
enum
//枚举
extern
//引入外部符号
float
//单精度浮点数
for
//for循环
goto
//goto语句
if
//if语句
int
//整型
long
//长整型
register
//寄存器关键字
int main()
{
register int a = 10;//建议把定义成寄存器变量
return 0;
}
return
//返回
short
//短整型
signed
//
int main()
{
int a = 10;
a = -2;
//int 定义的变量是有符号的
//signed int;
unsigned int num = 1;
return 0;
}
sizeof
//计算大小的
static
//静态的
struct
//结构体关键字
switch
typedef
//类型定义
union
//联合体/共用体
unsigned
void
//无or空
volatile
while
//循环
关键字typedef
int main()
{
//typedef - 类型定义 - 类型重定义
typedef unsigned int u_int;
unsigned int num = 20;
u_int num = 20;
return 0;
}
关键字static
在c语言中:
static是用来修饰变量和函数的
1、修饰局部变量-静态局部变量
2、修饰全局变量-静态全局变量
3、修饰函数-静态函数
修饰局部变量
#include <stdio.h>
#include <string.h>
//static修饰局部变量
//局部变量的生命周期变长
void test()
{
static int a = 1;//a 是一个静态的局部变量
a++;
printf("%d\n", a);
}
int main()
{
int i = 0;
while (i < 5)
{
test();
i++;
}
return 0;
}
2
3
4
5
6
修饰全局变量
在源文件main.c中编写
#include <stdio.h>
#include <string.h>
//static 修饰全局变量
//改变了变量的作用域 - 让静态的全局变量只能在自己所在的源文件内部使用
//出了源文件就没法再使用了
int main()
{
//extern - 声明外部符号的
extern int g_val;
printf("%d\n", g_val);
return 0;
}
在另外一个源文件add.c中编写
static int g_val = 2022;//全局变量
修饰全局变量
在源文件main.c中编写
#include <stdio.h>
#include <string.h>
//static修饰函数
//也是改变了函数的作用域- 不准确
//static修饰函数改变了函数的链接属性
//外部链接属性 ---> 内部链接属性
extern int Add(int, int);
int main()
{
int a = 10;
int b = 20;
int sum = Add(a, b);
printf("%d\n", sum);
return 0;
}
在源文件add.c中编写
/定义一个函数
int Add(int x, int y)
{
int z = x + y;
return z;
}
结果如下
30
在源文件add.c中加入static
/定义一个函数
static int Add(int x, int y)
{
int z = x + y;
return z;
}
运行结果不通过
#define定义常量和宏
#include <stdio.h>
#include <string.h>
//#define 定义标识符常量
#define MAX 100
//#define 可以定义宏-带参数
//函数的实现
Max(int x, int y)
{
if (x > y)
return x;
else
return y;
}
//宏的定义
#define MAX(X,Y) (X>Y?X:Y)
int main()
{
//int a = MAX;
int a = 10;
int b = 20;
//函数
int max = Max(a, b);
printf("max = %d\n", max);
//宏的方式
max = MAX(a, b);
//max = (a>b?a:b);
printf("max = %d\n", max);
return 0;
}
注:仅供学习参考使用。