google浏览器屏蔽广告:编写程序测试C++中所有数据类型在内存中占用的字节数。

来源:百度文库 编辑:高校问答 时间:2024/05/08 04:30:51
编写程序测试C++中所有数据类型在内存中占用的字节数。

怎么编~~~~~

#include <iostream>
using namespace std;

int main()
{
cout<<"short:"<<sizeof(short)<<endl;
cout<<"char:"<<sizeof(char)<<endl;
cout<<"int:"<<sizeof(int)<<endl;
cout<<"long:"<<sizeof(long)<<endl;
cout<<"float:"<<sizeof(float)<<endl;
cout<<"double:"<<sizeof(double)<<endl;
}

    要获得一个类型在内存中占用的字节数(即其大小),需要使用sizeof运算符。

    用法:

        sizeof(表达式 或 类型)

    所以可用以下代码来实现:

#include <iostream>
using namespace std;

int main()
{
     cout << "short:" << sizeof(short) << endl;
     cout << "char:" << sizeof(char) << endl;
     cout << "int:" << sizeof(int) << endl;
     cout << "long:" << sizeof(long) << endl;
     cout << "float:" << sizeof(float) << endl;
     cout << "double:" << sizeof(double) << endl;
     
     return 0;
}

    注意,sizeof计算得到的值类型为size_t,一般是一个无符号数。sizeof的计算发生在编译时,C99中规定也可以在运行时进行计算。另外,sizeof不会计算括号中写的表达式的值,因此在sizeof的括号中写的表达式的任何副作用都不会被结算。

参考:sizeof百科

http://baike.baidu.com/link?url=nBcOs7q9NwjciqE2BZ_JOxlweroJHAddbdAibQSEYKVdcH_wGXcEuC0qJM_OZgbiFFHLweAl_znbru8ASzsbD_

呵呵,这个也