- 功能:以字节位单位,返回一个表达式或一个数据类型所占的字节数
- 返回值类型:是size_t类型
- sizeof有无括号:
- sizeof不加括号,后面不可以直接跟数据类型
- sizeof加括号,后面既可以跟表达式也可以跟数据类型
- 注意事项
对引用类型执行sizeof运算得到被引用对象所占空间的大小
对指针执行sizeof运算得到指针本身所占空间大小
对解引用指针执行sizeof运算得到指针指向指向的对象所占空间的大小,指针不需有效
对数组执行sizeof运算得到整个数组所占空间的大小,等价于对数组中所有的元素各执行一次sizeof运算并将结果求和。注意,sizeof运算不会把数组转换指针来处理
对string对象或vector对象执行sizeof运算只返回该类型固定部分的大小,不会计算对象中的元素占用了多少空间
二话不说,来看代码:
#include <iostream>
#include <string>
using namespace std;
int main(){
int a = 12;
short int b = 12;
float c = 12.0f;
double d = 12.333;
long int e = 123;
long long int f = 1233;
char ch = '0';
cout << sizeof a << "," << sizeof b << "," << sizeof c << "," << sizeof d << "," << sizeof e << "," << sizeof f << "," << sizeof ch <<endl;
uint8_t ua = 1;
uint16_t ub = 2;
uint32_t uc = 3;
uint64_t ud = 4;
cout << sizeof ua << "," << sizeof ub << "," << sizeof uc << "," << sizeof ud <<endl;
char* pa = &ch;
int* pb = &a;
cout <<sizeof pa << "," << sizeof pb <<endl;
uint32_t& p = uc;
cout << sizeof p <<endl;
int array[10];
cout << sizeof array <<endl;
string s = "hello world";
string s_empty;
cout << sizeof s << "," << sizeof s_empty << endl;
return 0;
}