类型与变量
整型、浮点、const、typedef。
35 分钟
类型与变量
C 的类型系统直接映射硬件宽度。对照 /roadmaps/c,掌握整型、浮点、const 与 typedef 是读懂内核、驱动与任何 C 项目的基础。
学习目标
- 掌握基本数据类型与
sizeof - 使用
const与#define常量 - 用
typedef简化类型名 - 理解 C 中「无类、无对象」的变量模型
核心概念
基本类型
| C 类型 | 典型宽度 | Java 对照 |
|---|---|---|
char | 1 字节 | byte(语义不同) |
short | 2 字节 | short |
int | 4 字节 | int |
long | 4 或 8 字节 | long |
float / double | 4 / 8 字节 | 同名 |
_Bool / bool¹ | 1 字节 | boolean |
¹ C99 起可用 <stdbool.h> 的 bool、true、false。
变量与常量
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#define MAX_USERS 100
#define PI 3.14159265
typedef unsigned int user_id_t;
int main(void) {
int count = 42;
double price = 19.99;
bool active = true;
const int limit = MAX_USERS;
user_id_t uid = 1001;
printf("count=%d, size=%zu\n", count, sizeof(count));
printf("uid=%u, limit=%d, pi=%.2f\n", uid, limit, PI);
printf("int=%zu, long=%zu, ptr=%zu\n",
sizeof(int), sizeof(long), sizeof(void *));
/* limit = 200; // 编译错误:const 不可改 */
return 0;
}
#define:预处理宏,无类型检查const:编译期只读,比宏更安全stdint.h:固定宽度类型如uint32_t,跨平台代码推荐typedef:为类型起别名,不创建新类型
类型转换
C 允许隐式窄化转换(可能丢失精度)。显式转换:(double)count。与 Java 不同,C 无自动装箱。