欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > c/c++ >内容正文

c/c++

C++王者之路 | C++的sizeof 与C语言的sizeof

发布时间:2025/3/15 c/c++ 54 豆豆
生活随笔 收集整理的这篇文章主要介绍了 C++王者之路 | C++的sizeof 与C语言的sizeof 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

一、前言


我真正掌握的第一个编程语言是C语言,主要在stm32上使用。最近准备掌握C++去编写一些代码,在学习C++的过程中,有一些语法跟C语言类似。比如sizeof,在C编程里经常需要使用它。

二、代码对比


2.1、C版本

#include <stdio.h> #include <string.h> //#include <climits.h> /* 没有这个头文件 */ #include <limits.h> /* C语言需要包含这个头文件 */ int main() {int a = 255;printf("Hello world!\r\n"); printf("The size of n is %d \r\n",sizeof a); /* 打印变量a的大小(单位:byte) */printf("The size of int is %d \r\n",sizeof(int)); /* 打印变量类型的大小(单位:byte) */return 0; }

输出的结果:

2.2、C++版本

#include <iostream> #include <climits>int main() {using namespace std;int n_int = INT_MAX; /* climits头文件里的宏定义 */ short n_short = SHRT_MAX; /* climits头文件里的宏定义 */ long n_long = LONG_MAX; /* climits头文件里的宏定义 */ long long n_llong = LLONG_MAX; /* climits头文件里的宏定义 */ cout <<"int is " << sizeof(int) << "bytes." <<endl; /* sizeof打印变量类型的大小(单位:bytes) */ cout <<"short is " << sizeof n_short << "bytes." <<endl;cout <<"long is " << sizeof n_long << "bytes." <<endl; cout <<"long long is " << sizeof n_llong << "bytes." <<endl; /* sizeof打印变量的大小(单位:bytes) */cout << endl;cout << "Maximum values:" << endl;cout << "int: " <<n_int << endl; cout << "short: " <<n_short << endl;cout << "long: " <<n_long << endl;cout << "long long: " <<n_llong << endl << endl;cout << "Minimum int value = " << INT_MIN << endl; //int类型的最小值 cout << "Bits per byte = " << CHAR_BIT << endl; //打印char的位数 return 0; }

输出的结果:

三、区别


3.1、C与C++使用sizeof()的方法一样的。

sizeof 变量名; //返回变量名占用多少个字节(单位:Byte),比如int n ; sizeof n ; //返回变量n的大小(占了多少个字节) sizeof(变量名类型); //返回变量类型占用多少个字节(单位:Byte), 比如sizeof(char); //返回变量类型char占用了多少个字节

3.2、C与C++都可以包含某个头文件,了解各个变量类型的取值范围。

C: #include <limits.h>C++: #include <climits>

头文件的命名稍微有一点不一样,内容大部分是一样的。这个头文件其实就是通过定义一些宏来告诉用户,变量类型的取值范围。

总结

以上是生活随笔为你收集整理的C++王者之路 | C++的sizeof 与C语言的sizeof的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。