定義
sizeof操作符的作用是返回一個對象或類型名的長度,返回值的類型爲size_t,長度的單位是字節。sizeof表達式的結果是編譯時常量,該操作符有一下三種語法形式:
sizeof(type name);
sizeof(expr);
sizeof expr;
理解
將sizeof用於expo時,並沒有計算表達式expr的值。
使用sizeof所得的結果部分的
依賴所涉及的類型。
對char類型或值爲char類型的表達式做sizeof操作結果爲1。
對引用類型做sizeof操作將返回存放此引用類型對象所需的內存空間大小。
對指針做sizeof操作將返回存放指針所需的內存大小。
對數組做sizeof操作等效於將對其元素類型做sizeof操作的結果乘上數組元素的個數。
#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char * argv[]) {
char ch = 'B';
int i = 100;
int &ref = i;
int ar[10];
string str = "string";
cout << sizeof(ch) << endl << sizeof(char) << endl;
cout << sizeof(ref) << endl << sizeof(i) << endl;
cout << sizeof(ar) << endl << sizeof(ar[10]) << endl;
cout << sizeof(long)<< endl << sizeof(short) << endl;
cout << sizeof(str) << endl << sizeof("strin")<< endl;
return 0;
}
控制檯輸出:
1
1
4
4
40
4
8
2
24
6
Program ended with exit code: 0