c++ - 我在 [int,float,char 等] 中在 C++ 中命令不同值时得到相同的值
问题描述
输入
int main()
{
int a; //declaration
a=15; //initialisation
cout<<"sizeofint"<<sizeof(a)<<endl\n;
float b;
cout<<"size of float"<<sizeof(b)<<endl;
char c;
cout<<"size of char"<<sizeof(c)<<endl;
bool d;
cout<<"size of bool"<<sizeof(d)<<endl;
输出
size of int4
size of float4
size of char1
size of bool1
另一个例子
int a; //declaration
a=21; //initialisation
cout<<"sizeofint"<<sizeof(a)<<endl\n;
float b;
cout<<"size of float"<<sizeof(b)<<endl;
char c;
cout<<"size of char"<<sizeof(c)<<endl;
bool d;
cout<<"size of bool"<<sizeof(d)<<endl;
输出
size of int4
size of float4
size of char1
size of bool1
两个输出都一样!!!为什么?
解决方案
我认为您认为声明的工作方式存在误解。无论您输入的值有多大int
(即使它超出了它的范围)编译器仍然会保留相同数量的字节,这也取决于您的操作系统架构(通常是32-bit
或64-bit
)。例如,size_t
在一个32-bit
系统中有 4 个字节大小,而64-bit
它有 8 个字节大小(对于任何指针也是如此)。对于int
值,它默认为 4 个字节(在 ILP64 接口中,它的大小将是原来的两倍!)。Sizeof()
返回为某个变量保留了多少内存(以字节为单位)。
推荐阅读
- python - 在多个页面上识别 Python Selenium Webdriver 的站点
- javascript - 未捕获(承诺)类型错误:无法读取未定义的属性“拆分”?下一个使用 React-Router 的应用
- python - toolchain.py AttributeError:“字节”对象没有属性“编码”
- android - 没有找到重力LEFT的抽屉视图 - Android
- javascript - Service Worker - 不包括路径
- mongodb - 在 MongoDB 中使用 LIKE 等效项进行查找
- html - 如何使用复选框制作类显示块
- python - 切换git分支后Visual Studio Code Python IntelliSense数据库不同步?
- java - 在抽象方法中添加一般参数 (Java)
- css - CSS彩虹动画的同步