資料類型即是用來盛載資料的資料類型。常見6種類型︰
- 字元 Character (character, char)
- 整數 Integer (integer, int, short, long, byte)
- 浮點數 Floating-point number (float, double, real, double precision)
- 浮點數 Fixed-point number (fixed)
- 布林 Boolean
- 指標 Reference (pointer or handle)
當中整數和浮點數的資料型別都分為 signed
和 unsigned
。簡單來說, signed
是可以儲存負數值, unsigned
只可以儲存正數值。例如 signed short
的範圍是由 -32,768 至 32,767 ,而 unsigned short
的範圍是由 0 至 65,535 。
在 signed
和 unsigned
的資料型別中,我們可以將它分為兩類,一是長格式,二是短格式。
長格式 | ||
---|---|---|
char | signed char | unsigned char |
float | signed short int | unsigned short int |
double | signed int | unsigned int |
long double | signed long int | unsigned long int |
短格式 | ||
char | signed char | unsigned char |
float | short | unsigned short |
double | int | unsigned |
long double | long | unsigned long |
下面的表格是不同資料類型的正負參考表格。
包含正負的資料類型 | 不含正負的資料類型 |
---|---|
char, signed char | unsigned char |
short, short int, signed short, signed short int | unsigned short, unsigned short int |
int, signed int | unsigned, unsigned int |
long, long int, signed long, signed long int | unsigned long, unsigned long int |
long long, long long int, signed long long, signed long long int | unsigned long long, unsigned long long int |
在不同的平台或編譯器下,不同的資料型別可能會佔用不同大小的記憶體。我們可以透過下面的代碼查看資料型別佔用記憶體的大小。
|
|
運行上面的C編碼,使用了sizeof()操作符(又稱運算子),就可顯示不同資料型別所確實佔用的記憶體大小。sizeof()顯示出來的單位是bytes。
總結以上資料,我們可以得出︰
Bytes | Range |
---|---|
Integer | |
1 | -128 to 127 |
2 | -32,768 to +32,767 |
4 | -2,147,483,648 to +2,147,483,647 |
8 | -9,223,372,036,854,775,908 to +9,223,372,036,854,775,907 |
Floating-point | |
4 | -3.4×1038 to 3.4×1038 |
8 | -1.7×10308 to 1.7×10308 |