C++ 速查手冊
3.3 - 整數
整數利用三個關鍵字 short 、 int 及 long 進行宣告,另可與 signed 及unsigned 兩個修飾詞搭配,如下表
short | short int | signed short | signed short int |
unsigned short | unsigned short int | ||
int | signed | 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 |
通常 short 與 int 至少是 16 位元, long 至少為 32 位元,而 long long 至少為 64 位元 ,視所用機器及編譯器而定。 signed 表示帶正負號, unsigned 表示不帶正負號,這是說 unsigned 的值為 0 或正整數。
long long 為 C++11 新增的資料型態。
以下程式計算出各種宣告組合在 64 位元機器所佔的位元組數
#include <iostream>
int main() {
std::cout << "short : " << sizeof(short) << std::endl;
std::cout << "short int : " << sizeof(short int) << std::endl;
std::cout << "signed short : " << sizeof(signed short) << std::endl;
std::cout << "signed short int : " << sizeof(signed short int) << std::endl;
std::cout << "unsigned short : " << sizeof(unsigned short) << std::endl;
std::cout << "unsigned short int : " << sizeof(unsigned short int) << std::endl;
std::cout << "int : " << sizeof(int) << std::endl;
std::cout << "signed : " << sizeof(signed) << std::endl;
std::cout << "signed int : " << sizeof(signed int) << std::endl;
std::cout << "unsigned : " << sizeof(unsigned) << std::endl;
std::cout << "unsigned int : " << sizeof(unsigned int) << std::endl;
std::cout << "long : " << sizeof(long) << std::endl;
std::cout << "long int : " << sizeof(long int) << std::endl;
std::cout << "signed long : " << sizeof(signed long) << std::endl;
std::cout << "signed long int : " << sizeof(signed long int) << std::endl;
std::cout << "unsigned long : " << sizeof(unsigned long) << std::endl;
std::cout << "unsigned long int : " << sizeof(unsigned long int) << std::endl;
std::cout << "long long : " << sizeof(long long) << std::endl;
std::cout << "long long int : " << sizeof(long long int) << std::endl;
std::cout << "signed long long : " << sizeof(signed long long) << std::endl;
std::cout << "signed long long int: " << sizeof(signed long long int) << std::endl;
std::cout << "unsigned long long : " << sizeof(unsigned long long) << std::endl;
std::cout << "unsigned long long int: " << sizeof(unsigned long long int) << std::endl;
return 0;
}
/* 《程式語言教學誌》的範例程式
http://kaiching.org/
檔名:u0303.cpp
功能:示範 C++ 的整數型態
作者:張凱慶*/
編譯後執行,結果如下
$ g++ u0303.cpp |
$ ./a.out |
short : 2 |
short int : 2 |
signed short : 2 |
signed short int : 2 |
unsigned short : 2 |
unsigned short int : 2 |
int : 4 |
signed : 4 |
signed int : 4 |
unsigned : 4 |
unsigned int : 4 |
long : 8 |
long int : 8 |
signed long : 8 |
signed long int : 8 |
unsigned long : 8 |
unsigned long int : 8 |
long long : 8 |
long long int : 8 |
signed long long : 8 |
signed long long int: 8 |
unsigned long long : 8 |
unsigned long long int: 8 |
$ |
相關教學影片