C++ 不同数据类型占据的内存空间大小

首先这个没有标准答案(或者说没有一个统一的标准), 除非我们加上限定词, 就是在多少位的计算机上。 现在假设我们的电脑是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;
}

运行结果如下:





  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值