日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

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

c/c++

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

發(fā)布時間:2025/3/15 c/c++ 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++王者之路 | C++的sizeof 与C语言的sizeof 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

一、前言


我真正掌握的第一個編程語言是C語言,主要在stm32上使用。最近準備掌握C++去編寫一些代碼,在學(xué)習C++的過程中,有一些語法跟C語言類似。比如sizeof,在C編程里經(jīng)常需要使用它。

二、代碼對比


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; }

輸出的結(jié)果:

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的位數(shù) return 0; }

輸出的結(jié)果:

三、區(qū)別


3.1、C與C++使用sizeof()的方法一樣的。

sizeof 變量名; //返回變量名占用多少個字節(jié)(單位:Byte),比如int n ; sizeof n ; //返回變量n的大小(占了多少個字節(jié)) sizeof(變量名類型); //返回變量類型占用多少個字節(jié)(單位:Byte), 比如sizeof(char); //返回變量類型char占用了多少個字節(jié)

3.2、C與C++都可以包含某個頭文件,了解各個變量類型的取值范圍。

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

頭文件的命名稍微有一點不一樣,內(nèi)容大部分是一樣的。這個頭文件其實就是通過定義一些宏來告訴用戶,變量類型的取值范圍。

總結(jié)

以上是生活随笔為你收集整理的C++王者之路 | C++的sizeof 与C语言的sizeof的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。