C++ sizeof运算符

C++ sizeof运算符教程

C++ 中,sizeof 运算符用于获取一个 变量 或者 数据类型 所占的内存的字节大小。

C++ sizeof运算符详解

语法

sizeof(type); sizeof(varname);

参数

参数 描述
type 要获取的数据类型
varname 要获取的变量

返回值

返回数据类型或者变量所占的内存大小。

说明

使用 sizeof 运算符,既可以获取指定的数据类型,也可以获取一个变量所占的内存大小。

案例

获取数据类型的字节大小

使用 sizeof 运算符,实现获取数据类型的字节大小

#include <iostream> using namespace std; int main(int argc, char **argv) { cout << "嗨客网(www.haicoder.net)\n" << endl; //使用 sizeof 运算符,实现获取数据类型的字节大小 int sizeofShort = sizeof(short); int sizeofInt = sizeof(int); int sizeofLL = sizeof(long long); int sizeofChar = sizeof(char); int sizeofFloat = sizeof(float); int sizeofDouble = sizeof(double); cout << "sizeofShort = " << sizeofShort << " sizeofInt = " << sizeofInt << " sizeofLL = " << sizeofLL << endl; cout << "sizeofChar = " << sizeofChar << endl; cout << "sizeofFloat = " << sizeofFloat << " sizeofDouble = " << sizeofDouble << endl; }

程序运行后,控制台输出如下:

24_C sizeof运算符.png

我们使用了 sizeof 运算符获取了各种数据类型所占的内存的字节大小。

获取变量的字节大小

使用 sizeof 运算符,实现获取变量的字节大小

#include <iostream> using namespace std; int main(int argc, char **argv) { cout << "嗨客网(www.haicoder.net)\n" << endl; //使用 sizeof 运算符,实现获取变量的字节大小 short a = 1; int b = 2; long long c = 3; int sizeofA = sizeof(a); int sizeofB = sizeof(b); int sizeofC = sizeof(c); char d = 'a'; int sizeofD = sizeof(d); float e = 1.223; double f = 1.11111; int sizeofE = sizeof(e); int sizeofF = sizeof(f); cout << "sizeofA = " << sizeofA << " sizeofB = " << sizeofB << " sizeofC = " << sizeofC << endl; cout << "sizeofD = " << sizeofD << endl; cout << "sizeofE = " << sizeofE << " sizeofF = " << sizeofF << endl; }

程序运行后,控制台输出如下:

25_C sizeof运算符.png

我们使用了 sizeof 运算符获取了各种数据类型的变量所占的内存的字节大小。

C++ sizeof运算符总结

在 C++ 中,sizeof 运算符用于获取一个变量或者数据类型所占的内存的字节大小。