C++ sizeof 运算符

sizeof 是一个关键字,它是一个编译时运算符,用于判断变量或数据类型的字节大小。

sizeof 运算符可用于获取类、结构、共用体和其他用户自定义数据类型的大小。

使用 sizeof 的语法如下:

sizeof (data type)

其中,data type 是要计算大小的数据类型,包括类、结构、共用体和其他用户自定义数据类型。

请尝试下面的实例,理解 C++ 中 sizeof 的用法。复制并黏贴下面的 C++ 程序到 test.cpp 文件中,编译并运行程序。

 1 #include <iostream>
 2 using namespace std;
 3  
 4 int main()
 5 {
 6    cout << "Size of char : " << sizeof(char) << endl;
 7    cout << "Size of int : " << sizeof(int) << endl;
 8    cout << "Size of short int : " << sizeof(short int) << endl;
 9    cout << "Size of long int : " << sizeof(long int) << endl;
10    cout << "Size of float : " << sizeof(float) << endl;
11    cout << "Size of double : " << sizeof(double) << endl;
12    cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
13    return 0;
14 }

当上面的代码被编译和执行时,它会产生下列结果,结果会根据使用的机器而不同:

1 Size of char : 1
2 Size of int : 4
3 Size of short int : 2
4 Size of long int : 4
5 Size of float : 4
6 Size of double : 8
7 Size of wchar_t : 4

 

原文链接: https://www.cnblogs.com/ybqjymy/p/12356533.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++ sizeof 运算符

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/331508

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午6:04
下一篇 2023年3月1日 下午6:04

相关推荐