首先这个没有标准答案(或者说没有一个统一的标准), 除非我们加上限定词, 就是在多少位的计算机上。 现在假设我们的电脑是32位机(事实上, 我的电脑是32 位的)。
参考上图, 注意一下几点:
(1)int 的表达用了4bytes, 表示的范围还是很大的, 无符号的整型达到了0——429,467,295, 所以一般没有什么溢出问题, 不用考虑。
(2)signed int能够表示负整数。
(3)事实上, 有三种表示integer type , 分别是是short, int, long, 三者的size是按照 non-decreasing order。 int 一般代表short 或者long 在中的一种。一般而言, 你并不需要worry about 该选用哪一个类型, 除非你对memory usage 的 特别注意, 或者你使用的数字十分大, short 不满足要求, 非得使用long。类似的, 浮点数也有三种类型, 为float, double, long double, 精度也是逐渐升高(none-decreasing order of precision)。 记住: 在计算机中, 对于实数(浮点数)的表示是不精确的。 这有点让人confusing, 因为int的表示的精度是高于浮点数例如double的精度的, It is!
还有几点注意, 参见下图:
测试程序如下(code::blocks):
#include <iostream>
using namespace std;
int main() {
int a1 = 1;
int bytes_of_int = sizeof(a1);
short a2 = 1;
int bytes_of_short = sizeof(a2);
long a3 = 1;
int bytes_of_long = sizeof(a3);
char b = '1';// char 型用单引号
int bytes_of_char = sizeof(b);
bool c = true;
int bytes_of_bool = sizeof(c);
double d = 1.0;
int bytes_of_double = sizeof(d);
float e = 1.0;
int bytes_of_float = sizeof(e);
long double f = 1.0;
int bytes_of_LongDouble = sizeof(f);
cout << "int: " << bytes_of_int << endl;
cout << "short: " << bytes_of_short << endl;
cout << "long: " << bytes_of_long << endl;
cout << "char: " << bytes_of_char << endl;
cout << "bool: " << bytes_of_bool << endl;
cout << "double: " << bytes_of_double << endl;
cout << "float: " << bytes_of_float << endl;
cout << "long double: " << bytes_of_LongDouble << endl;
return 0;
}
运行结果如下: