變數宣告時需指定資料型別,作業系統據此配置記憶體空間並決定位元解讀方式。C++ 提供七大基本型別與豐富的衍生型別機制。
| 分類 | 關鍵字 | 典型大小 | 範圍/精度 |
|---|---|---|---|
| 布林 | bool | 1 byte | true/false |
| 字元 | char | 1 byte | -128~127 或 0~255 |
| 整數 | int | 4 bytes | -2,147,483,648 ~ 2,147,483,647 |
| 單精度 | float | 4 bytes | ±3.4e±38 (~7 位有效數字) |
| 雙精度 | double | 8 bytes | ±1.7e±308 (~15 位有效數字) |
| 無型別 | void | N/A | 不完整型別 |
| 寬字元 | wchar_t | 2/4 bytes | 1 寬字元 |
signed/unsigned/short/long 修飾基本整數型別:
| 型別 | 大小 | 範圍 |
|---|---|---|
signed char | 1 byte | -128 ~ 127 |
unsigned char | 1 byte | 0 ~ 255 |
short int | 2 bytes | -32,768 ~ 32,767 |
unsigned short | 2 bytes | 0 ~ 65,535 |
long int | 4/8 bytes | 平台相關 |
unsigned long | 4/8 bytes | 0 ~ 2³²-1 或 2⁶⁴-1 |
實作定義:確切大小/範圍依編譯器/平台,必須用 sizeof 確認。
#include
using namespace std;
int main() {
cout << "char: " << sizeof(char) << endl;
cout << "int: " << sizeof(int) << endl;
cout << "short: " << sizeof(short) << endl;
cout << "long: " << sizeof(long) << endl;
cout << "float: " << sizeof(float) << endl;
cout << "double: " << sizeof(double) << endl;
cout << "wchar_t: " << sizeof(wchar_t) << endl;
return 0;
}
輸出範例 (64-bit Linux):
char: 1 int: 4 short: 2 long: 8 float: 4 double: 8 wchar_t: 4
為既有型別建立新名稱,提升可讀性與可攜性:
typedef int Feet; // Feet 成為 int 別名
Feet distance = 100; // 合法
typedef long long int64; // 固定寬度別名 (C++11 建議用 )
typedef void (*FuncPtr)(int); // 函數指標別名
現代 C++ 偏好 using:using Feet = int;、using FuncPtr = void(*)(int);,支援模板別名。
使用者定義的離散值集合,增強型別安全與可讀性。
enum Color { RED, GREEN, BLUE };
Color c = RED; // 隱性轉換為 int (0)
int i = GREEN; // 合法但不安全
enum { A=10, B=20, C }; → C=21。enum class (C++11)
enum class Color { RED, GREEN, BLUE };
Color c = Color::RED; // 作用域限定
// int i = Color::RED; // 錯誤:不可隱性轉換
int i = static_cast(Color::RED); // 顯式轉換
enum class Flag : uint8_t { A=1, B=2 };Flag f = Flag::A | Flag::B; (需多載運算子)| 需求 | 建議型別 |
|---|---|
| 開關狀態 | bool |
| ASCII 字元 | char |
| Unicode 代碼點 | char32_t (C++11) / wchar_t |
| 一般整數計數 | int |
| 大整數/位元掩碼 | uint32_t/uint64_t |
| 一般浮點運算 | double |
| 記憶體/頻寬受限 | float/half |
| 固定選項集合 | enum class |
| 型別別名/可攜性 | using + <cstdint> |
sizeof 與 <climits>/<cfloat> 驗證。enum class 獲得型別安全與作用域隔離。using 取代 typedef,支援模板別名。<cstdint> 固定寬度型別,消除平台差異。