C++王者之路 | C++的sizeof 与C语言的sizeof
生活随笔
收集整理的這篇文章主要介紹了
C++王者之路 | C++的sizeof 与C语言的sizeof
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、前言
我真正掌握的第一個編程語言是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的位數(shù) return 0; }輸出的結果:
三、區(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>頭文件的命名稍微有一點不一樣,內容大部分是一樣的。這個頭文件其實就是通過定義一些宏來告訴用戶,變量類型的取值范圍。
總結
以上是生活随笔為你收集整理的C++王者之路 | C++的sizeof 与C语言的sizeof的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python连接impala_pytho
- 下一篇: 烽火交换机s5800配置说明_如何通过单