[編程] C 的資料類型

資料類型即是用來盛載資料的資料類型。常見6種類型︰

  1. 字元 Character (character, char)
  2. 整數 Integer (integer, int, short, long, byte)
  3. 浮點數 Floating-point number (float, double, real, double precision)
  4. 浮點數 Fixed-point number (fixed)
  5. 布林 Boolean
  6. 指標 Reference (pointer or handle)

當中整數和浮點數的資料型別都分為signed和unsigned。簡單來說,signed是可以儲存負數值,unsigned只可以儲存正數值。例如signed short的範圍是由-32,768至32,767,而unsigned short的範圍是由0至65,535。

在signed和unsigned的資料型別中,我們可以將它分為兩類,一是長格式,二是短格式。

長格式
charsigned charunsigned char
floatsigned short intunsigned short int
doublesigned intunsigned int
long doublesigned long intunsigned long int
短格式
charsigned charunsigned char
floatshortunsigned short
doubleintunsigned
long doublelongunsigned 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

在不同的平台或編譯器下,不同的資料型別可能會佔用不同大小的記憶體。我們可以透過下面的代碼查看資料型別佔用記憶體的大小。

#include <stdio.h>

int main(void)
{
	printf("%s", "+-------------------------------+-------+\n");
	printf("%s", "| Primitive Data Types of C\t| bytes\n");
	printf("%s", "+-------------------------------+-------+\n");
	printf(" char\t\t\t\t| %d\n", sizeof(char));
	printf(" short\t\t\t\t| %d\n", sizeof(short));
	printf(" int\t\t\t\t| %d\n", sizeof(int));
	printf(" long\t\t\t\t| %d\n", sizeof(long));
	printf(" float\t\t\t\t| %d\n", sizeof(float));
	printf(" long int\t\t\t| %d\n", sizeof(long int));
	printf(" long long int\t\t\t| %d\n", sizeof(long long int));
	printf(" double\t\t\t\t| %d\n", sizeof(double));
	printf(" long double\t\t\t| %d\n", sizeof(long double));
	printf("%s", "+-------------------------------+-------+\n");
	return 0;
}

運行上面的C編碼,使用了sizeof()操作符(又稱運算子),就可顯示不同資料型別所確實佔用的記憶體大小。sizeof()顯示出來的單位是bytes。

總結以上資料,我們可以得出︰

BytesRange
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)