sizeof 操作符

定义

sizeof操作符的作用是返回一个对象或类型名的长度,返回值的类型为size_t,长度的单位是字节。sizeof表达式的结果是编译时常量,该操作符有一下三种语法形式:

1
2
3
sizeof(type name);
sizeof(expr);
sizeof expr;

理解

  • 将sizeof用于expo时,并没有计算表达式expr的值。

  • 使用sizeof所得的结果部分的依赖所涉及的类型。

  • 对char类型或值为char类型的表达式做sizeof操作结果为1。

  • 对引用类型做sizeof操作将返回存放此引用类型对象所需的内存空间大小。

  • 对指针做sizeof操作将返回存放指针所需的内存大小。

  • 对数组做sizeof操作等效于将对其元素类型做sizeof操作的结果乘上数组元素的个数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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
2
3
4
5
6
7
8
9
10
11
1
1
4
4
40
4
8
2
24
6
Program ended with exit code: 0