C語言有五種基本數據類型:字符、整型、單精度實型、雙精度實型和空類型。儘管這幾種類型數據的長度和範圍隨處理器的類型和C語言編譯程序的實現而異,但以b i t爲例,整數與CPU字長相等,一個字符通常爲一個字節,浮點值的確切格式則根據實現而定。對於多數微機,表2 - 1給出了五種數據的長度和範圍。
表中的長度和範圍的取值是假定C P U的字長爲1 6 b i t。
C語言還提供了幾種聚合類型(aggregate types),包括數組、指針、結構、共用體(聯合)、位域和枚舉。這些複雜類型在以後的章節中討論。
除v o i d類型外,基本類型的前面可以有各種修飾符。修飾符用來改變基本類型的意義,以便更準確地適應各種情況的需求。修飾符如下:
• signed(有符號)。
• unsigned(無符號)。
• long(長型符)。
• short(短型符)。修飾符s i g n e d、s h o r t、l o n g和u n s i g n e d適用於字符和整數兩種基本類型,而l o n g還可用於d o u b l e(注意,由於long float與d o u b l e意思相同,所以A N S I標準刪除了多餘的long float)。
表2 - 2給出所有根據A N S I標準而組合的類型、字寬和範圍。切記,在計算機字長大於1 6位的系統中,short int與signed char可能不等。
*表中的長度和範圍的取值是假定C P U的字長爲1 6 b i t。因爲整數的缺省定義是有符號數,所以s i n g e d這一用法是多餘的,但仍允許使用。某些實現允許將u n s i g n e d用於浮點型,如unsigned double。但這一用法降低了程序的可移
植性,故建議一般不要採用。爲了使用方便,C編譯程序允許使用整型的簡寫形式:
• short int 簡寫爲s h o r t。
• long int 簡寫爲l o n g。
• unsigned short int 簡寫爲unsigned short。
• unsigned int 簡寫爲u n s i g n e d。
• unsigned long int 簡寫爲unsigned long。
即,i n t可缺省。
void display(char *str , int size)
{
cout<<str<<" :/t"<<size <<endl ;
}
void main()
{
display( "sizeof(enum)" ,sizeof(enum) ) ;
display( "sizeof(void *)" ,sizeof(void *) ) ;
cout<<"/n" ;
display( "sizeof(bool)" ,sizeof(bool) ) ;
display( "sizeof(char )" ,sizeof(char ) ) ;
display( "sizeof(unsigned char )" ,sizeof(unsigned char ) ) ;
cout<<"/n" ;
display( "sizeof( int)" ,sizeof( int) ) ;
display( "sizeof(unsigned (int) )" ,sizeof(unsigned int ) ) ;
display( "sizeof( short (int) )" ,sizeof(short int ) ) ;
display( "sizeof(short unsigned int = unsigned short (int) )" ,sizeof(short unsigned int ) ) ;
display( "sizeof( long (int) )" ,sizeof( long int ) ) ;
display( "sizeof(long unsigned int = unsigned long (int) )" ,sizeof(long unsigned int ) ) ;
cout<<"/n" ;
display( "sizeof( float )" ,sizeof( float ) ) ;
display( "sizeof( long float = double )" ,sizeof( long float ) ) ;
cout<<"/n" ;
display( "sizeof( dounble )" ,sizeof( double ) ) ;
display( "sizeof(long dounble )" ,sizeof( long double ) ) ;
cout<<"/n/n" ;
}
32bit---compute :
輸出:
sizeof(enum) : 4
sizeof(void *) : 4
sizeof(bool) : 1
sizeof(char ) : 1
sizeof(unsigned char ) : 1
sizeof( int) : 4
sizeof(unsigned (int) ) : 4
sizeof( short (int) ) : 2
sizeof(short unsigned int = unsigned short (int) ) : 2
sizeof( long (int) ) : 4
sizeof(long unsigned int = unsigned long (int) ) : 4
sizeof( float ) : 4
sizeof( long float = double ) : 8
sizeof( dounble ) : 8
sizeof(long dounble ) : 8