c语言的32个关键字大全(建议收藏)

在 C 语言里,关键字(Keywords)是编译器预留的“专用单词”,它们具有固定含义,不能当作变量名、函数名或宏名使用。全部关键字都由小写字母组成,共 32 个(C99 之前)。记住:写代码时,只要拼写与关键字完全一致,编译器就会按既定规则解释,不会征求你的意见。

C语言关键字清单速览

关键字作用简述
auto 声明自动变量,默认存储类型
break 跳出当前循环或 switch
case switch 语句分支标签
char 字符类型
const 只读限定
continue 跳过本轮循环剩余语句
default switch 默认分支
do do…while 循环入口
double 双精度浮点
else if 否定分支
enum 枚举类型
extern 声明外部变量/函数
float 单精度浮点
for for 循环
goto 无条件跳转
if 条件语句
int 整型
long 长整型
register 建议寄存器变量
return 函数返回
short 短整型
signed 有符号类型
sizeof 计算类型/对象大小
static 静态存储期
struct 结构体
switch 多分支选择
typedef 类型重命名
union 共用体
unsigned 无符号类型
void 空类型
volatile 易变变量
while while 循环

关键字与标识符的区别

标识符是你给变量、函数、宏起的名字;关键字却是“国家保护动物”,不能占用。以下代码会报错:

int float = 3;   /* ❌ float 是关键字,不能当变量名 */

编译器提示:error: expected identifier or '(' before 'float'

存储类关键字:auto、register、static、extern

它们决定变量“住在哪里、寿命多久”。

#include <stdio.h>
void demo(void)
{
    auto   int a = 1;   /* 默认,栈上分配 */
    register int b = 2; /* 建议放寄存器,不能取地址 */
    static int c = 3;   /* 只初始化一次,保留上次值 */
    printf("%d %d %d\n", a, b, c++);
}

int main(void)
{
    demo();  /* 输出 1 2 3 */
    demo();  /* 输出 1 2 4 */
    return 0;
}

类型限定关键字:const、volatile

const 告诉编译器“只读”;volatile 告诉编译器“别优化,可能随时变”。

const volatile int *pReg = (int *)0x4000;
/* 硬件寄存器:程序不能改,但硬件会改 */

构造类型关键字:struct、union、enum

#include <stdio.h>
struct Point { int x, y; };
union  Data  { int i; float f; };
enum   Color { RED=1, GREEN, BLUE };

int main(void)
{
    struct Point p = {3, 4};
    union  Data  d = {.f = 3.14f};
    enum   Color c = GREEN;
    printf("%d %f %d\n", p.x, d.f, c); /* 3 3.140000 2 */
    return 0;
}

流程控制关键字示例

#include <stdio.h>
int main(void)
{
    for (int i = 1; i <= 10; ++i) {
        if (i % 2 == 0) continue; /* 跳过偶数 */
        if (i > 7) break;         /* 大于 7 结束 */
        printf("%d ", i);         /* 输出 1 3 5 7 */
    }
    putchar('\n');
    return 0;
}

运行结果:

1 3 5 7

sizeof 不是函数

printf("%zu\n", sizeof(int));   /* 合法,关键字 */
printf("%zu\n", sizeof 3.14);   /* 括号可省 */

typedef 与 #define 的区别

typedef unsigned char uint8;  /* 创建新类型 */
#define UINT8 unsigned char   /* 纯文本替换 */

uint8  a = 255;   /* 类型检查 */
UINT8  b = 255;   /* 无类型检查 */

C99 新增关键字

C99 起又引入 inline、restrict、_Bool、_Complex、_Imaginary 等,但传统 32 个关键字仍是面试最常考范围。

给初学者的记忆口诀

  • 类型先记 char int float double,长短加上 short long signed unsigned;
  • 流程掌握 if else switch case default break continue for while do goto return;
  • 构造 struct union enum typedef sizeof;
  • 存储 auto register static extern const volatile void。

每天默背一遍,一周就能脱口而出。

posted @ 2025-11-24 17:30  像风一样的博主  阅读(15)  评论(0)    收藏  举报