C 語言簡史與地位
- 1972 年:Ken Thompson 开發 B 語言 (源自 BCPL)。
- 1972-1973:Dennis Ritchie 在貝爾實驗室基於 B 語言開發 C 語言,為 Unix 核心重寫奠基。
- 1978:K&R C (The C Programming Language) 成為事實標準。
- 1989/1990:ANSI C (C89/C90) 國際標準化。
- 1999:C99 新增
// 註釋、stdint.h、complex.h、VLA、inline、restrict。
- 2011:C11 多執行緒、原子操作、泛型選擇、邊界檢查介面。
- 2018/2023:C17/C23 持續演進 (C23 引入
typeof、auto、constexpr、bitint、屬性語法 [[...]])。
核心特性
- 接近硬體:直接操作位元組、位、記憶體位址,適合系統程式、嵌入式、驅動程式。
- 高效能:編譯為原生機器碼,零運行時開銷,手動記憶體管理。
- 可移植:標準庫抽象平台差異,標準 C 代碼重新編譯即可跨平台 (含超算、單晶片)。
- 簡潔核心:僅 32/37/44 個關鍵字 (C89/C99/C23)、簡潔語法、豐富運算子。
- 模組化:標頭檔 (.h) + 實作檔 (.c),分開編譯連結。

基本程式結構
#include <stdio.h> // 標頭檔:函數宣告、巨集、型別定義
int main(void) { // 程式入口,回傳 int 給作業系統
printf("Hello, C!\n"); // 標準輸出
return 0; // 0 代表成功
}
資料類型完整分類
| 類別 | 關鍵字 | 典型大小/範圍 (x86-64) | 格式化字串 |
| 整數 | char / signed char / unsigned char | 1 byte / -128~127 / 0~255 | %c / %hhd / %hhu |
| short / unsigned short | 2 bytes / -32768~32767 / 0~65535 | %hd / %hu |
| int / unsigned int | 4 bytes / -2.147G~2.147G / 0~4.294G | %d / %u |
| long / unsigned long | 8 bytes (LP64) / 4 bytes (Windows LLP64) | %ld / %lu |
| long long / unsigned long long | 8 bytes / ±9.22e18 / 0~1.84e19 | %lld / %llu |
| 浮點數 | float | 4 bytes / ~7 位有效數字 / ±3.4e38 | %f / %e / %g |
| double | 8 bytes / ~15 位 / ±1.7e308 | %lf / %le / %lg |
| long double | 16 bytes (x86 80-bit extended) / ~19 位 | %Lf |
| 布林 | _Bool (C99) / bool (stdbool.h) | 1 byte / 0 或 1 | %d |
| 字符 | char (實為小整數) | ASCII/UTF-8 代碼單元 | %c |
| 衍生類型 | 陣列、指標、結構體、聯合、枚舉、函數指標 | 組合現有類型 | 視具體類型 |
指標 — C 語言靈魂
int a = 10;
int *p = &a; // p 存放 a 的位址
printf("%d\n", *p); // 解引用:讀取 p 指向的值 (10)
*p = 20; // 透過指標修改 a (a 變 20)
void swap(int *x, int *y) { // 指標傳參實現交換
int t = *x; *x = *y; *y = t;
}
& 取址,* 解引用。
- 指標算術:
p+1 移動 sizeof(*p) 位元組。
- 空指標:
NULL / 0 / (void*)0。
- 函數指標:
int (*cmp)(const void*, const void*) — 回調、qsort、狀態機核心。
記憶體管理
- 靜態/全域/堆疊:自動生命週期 (編譯期/函數調用)。
- 堆疊:
malloc/calloc/realloc 分配,free 釋放,**程式員完全負責**。
- 常見錯誤:記憶體洩漏、重複釋放、使用已釋放記憶體、緩衝區溢位、雙重釋放。
- 工具:Valgrind (Memcheck)、AddressSanitizer (ASan,
-fsanitize=address)、malloc_debug。
進階主題速覽
- 結構體:
struct Point { int x, y; }; — 組合異構數據,記憶體連續佈局。
- 聯合:
union Data { int i; float f; char str[20]; }; — 共享記憶體,節省空間,型別遊戲。
- 位欄位:
struct { unsigned int flag:1; unsigned int len:7; }; — 精確控制位佈局。
- 前置處理器:
#define、#include、#ifdef 條件編譯、#pragma 編譯器指示。
- 標準庫:
<stdio.h> I/O、<stdlib.h> 工具、<string.h> 字串、<math.h> 數學、<time.h> 時間、<threads.h> (C11) 執行緒、<stdatomic.h> (C11) 原子操作。
學習建議
- 手寫編譯運行每個範例,觀察記憶體佈局 (配合 GDB/LLDB 偵錯)。
- 深入理解指標與陣列關係、指標與函數參數傳遞。
- 閱讀開源專案核心代碼 (Linux 核心、Redis、Nginx、SQLite、musl libc)。
- 練習實作資料結構:鏈表、哈希表、B+樹、執行緒池、記憶體分配器。
- 掌握靜態分析 (Cppcheck、Clang Static Analyzer) 與動態檢測 (ASan、TSan、UBSan)。