整型是 C 語言最基礎的數據類型,但其位寬、範圍、修飾符組合往往讓開發者困惑。本文系統梳理 int、short、long、long long 及其有符號/無符號變體,涵蓋聲明、初始化、常量表示、取值範圍與移植性考量。
| 名稱 | 完整聲明 | 縮寫 | 位寬(典型) | 有符號範圍 | 無符號範圍 |
|---|---|---|---|---|---|
| 整型 | int | int | 16/32 | -32,768 ~ 32,767 / -2,147,483,648 ~ 2,147,483,647 | 0 ~ 65,535 / 0 ~ 4,294,967,295 |
| 短整型 | short int | short | 16 | -32,768 ~ 32,767 | 0 ~ 65,535 |
| 長整型 | long int | long | 32/64 | -2,147,483,648 ~ 2,147,483,647 | 0 ~ 4,294,967,295 |
| 超長整型 | long long int | long long | 64 | -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807 | 0 ~ 18,446,744,073,709,551,615 |
註:具體位寬由實現定義,sizeof 運算符可在運行時查詢。
short、long、signed、unsigned 可自由組合(C99 新增 long long),產生 12 種標準整型:
short int, long int, long long int, unsigned int, unsigned long int, unsigned short int, unsigned long long int, signed int, signed long int, ... // 顯式 signed 僅為文檔化
默認規則: 無 unsigned 即為有符號;int 可省略(如 unsigned long 等同 unsigned long int)。
int sum; long int population; unsigned int count; int width = 150, height = 60; // 同類型多變量聲明並初始化
0,如 054、05670x/0X,如 0x3D、0XE0254、745長整型後綴: L 或 l(推薦大寫 L 避免與數字 1 混淆),如 245L、7850L。C99 另提供 ULL 等後綴對應 unsigned long long。
short ≤ int ≤ long ≤ long long,各類型最小位寬分別為 16、16、32、64 位。int=short=16、long=32;32/64 位機常見 short=16、int=long=32/64、long long=64。sizeof(type) * CHAR_BIT 獲取精確位數(CHAR_BIT 通常為 8,定義於 <limits.h>)。printf("%zu\n", sizeof(int) * 8); // C99 %zu 對應 size_t
<stdint.h> 固定寬度類型為消除移植性疑慮,C99 在 <stdint.h> 提供精確寬度類型:
int8_t, int16_t, int32_t, int64_t(精確寬度)int_least8_t, int_fast32_t(最小/最快寬度)intptr_t, uintptr_t(足以容納指針)intmax_t, uintmax_t(最大寬度)現代項目推薦優先使用固定寬度類型,明確語義並消除平台差異。