大家好,我是程序员柏风,AI 最全的 Vibecoding 学习地图 http://coderoadmap.cn 作者。
类型与变量
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 无自动装箱。
与 C++/Java 对照
| 特性 | C | C++ | Java |
|---|---|---|---|
| 布尔 | _Bool / bool | bool | boolean |
| 字符串 | char[] | std::string | String |
| 常量 | #define / const | constexpr | final |
| 类型别名 | typedef | using / typedef | 无(类包装) |
| 一切皆对象 | 否 | 否 | 是(基本类型除外) |
C++ 的 auto、Java 的 var 在 C 中不存在;变量类型必须显式声明(或用宏生成)。
练习
- 打印
char、int、long、double、void *的sizeof - 用
typedef定义score_t为int,写函数接受该类型 - 对比
#define N 10与const int N = 10的差异 - 用
stdint.h声明uint16_t port = 8080
小结
C 类型贴近硬件;const、typedef、stdint 是规范编码的基础。 下一课学习控制流与运算符。