C 的資料類型

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)

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

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

長格式
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

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#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。

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

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
Made in Hong Kong