在C語言中,常用的數據類型的大小是隨操作系統和編譯器等因素變化的。
1 #include <stdio.h>
2 #include <float.h>
3
4 #define PR(x) printf("%11s: %2lu bytes\n", #x, (unsigned long)sizeof(x))
5
6 int main(void)
7 {
8 PR(size_t);
9 PR(void *);
10 PR(char);
11 PR(short);
12 PR(int);
13 PR(long);
14 PR(long long);
15 PR(float);
16 PR(double);
17 PR(long double);
18 printf("\n---- DIG -------EPSILON -----------MIN -----------MAX\n");
19 printf(" FLT %3d %-14E %-14E %-14E\n", FLT_DIG, FLT_EPSILON, FLT_MIN, FLT_MAX);
20 printf(" DBL %3d %-14E %-14E %-14E\n", DBL_DIG, DBL_EPSILON, DBL_MIN, DBL_MAX);
21 printf("LDBL %3d %-14LE %-14LE %-14LE\n", LDBL_DIG, LDBL_EPSILON, LDBL_MIN, LDBL_MAX);
22 printf("---- --- -------------- -------------- --------------\n");
23 return 0;
24 }
這個程序在 ideone.com 中的運行結果如下所示(http://ideone.com/jH1dT):
size_t: 4 bytes void *: 4 bytes char: 1 bytes short: 2 bytes int: 4 bytes long: 4 bytes long long: 8 bytes float: 4 bytes double: 8 bytes long double: 12 bytes ---- DIG -------EPSILON -----------MIN -----------MAX FLT 6 1.192093E-07 1.175494E-38 3.402823E+38 DBL 15 2.220446E-16 2.225074E-308 1.797693E+308 LDBL 18 1.084202E-19 3.362103E-4932 1.189731E+4932 ---- --- -------------- -------------- --------------
實際上,這是一個 32-bit 的 linux 操作系統,編譯器是 gcc 4.3.4。
這個程序在 openSuSE 12.1 64-bit 操作系統中的運行結果如下所示(編譯器是 gcc 4.6.2):
size_t: 8 bytes void *: 8 bytes char: 1 bytes short: 2 bytes int: 4 bytes long: 8 bytes long long: 8 bytes float: 4 bytes double: 8 bytes long double: 16 bytes ---- DIG -------EPSILON -----------MIN -----------MAX FLT 6 1.192093E-07 1.175494E-38 3.402823E+38 DBL 15 2.220446E-16 2.225074E-308 1.797693E+308 LDBL 18 1.084202E-19 3.362103E-4932 1.189731E+4932 ---- --- -------------- -------------- --------------
上述結果中,long double 是 16 bytes 的,但是實際上其范圍和精度是和 12 bytes 的是一樣的,可能是在 64-bit 操作系統中為了對齊字節邊界的考慮吧。