C++语言程序设计

| 例3-1

#include <iostream.h>
int main (void)
{
cout << "char size = " << sizeof(char) << " bytes\n";
cout << "char* size = " << sizeof(char*) << " bytes\n";
cout << "short size = " << sizeof(short) << " bytes\n";
cout << "int size = " << sizeof(int) << " bytes\n";
cout << "long size = " << sizeof(long) << " bytes\n";
cout << "float size = " << sizeof(float) << " bytes\n";
cout << "double size = " << sizeof(double) << " bytes\n";
cout << "1.55 size = " << sizeof(1.55) << " bytes\n";
cout << "1.55L size = " << sizeof(1.55L) << " bytes\n";
cout << "HELLO size = " << sizeof("HELLO") << " bytes\n";
}
我们运行这个程序，产生下面的结果（在作者的PC机上）：
char size = 1 bytes
char* size = 2 bytes
short size = 2 bytes
int size = 2 bytes
long size = 4 bytes
float size = 4 bytes
double size = 8 bytes
1.55 size = 8 bytes
1.55L size = 10 bytes
HELLO size = 6 bytes

| 表3-10

类型 | 运算 | 运算符
求字节数运算符 | 求字节大小 | sizeof

下表给出了常用数据类型的字节数。具体的例子可参考书中给出的例子。当我们进行算术运算时，如果运算结果超出变量所能表达的数据范围时，就会发生溢出。如果我们能够利用sizeof运算符计算变量所占的字节数，就可算出变量的数据范围，从而可以避免可能出现的错误。
下表给出了常用数据类型的字节数。具体的例子可参考书中给出的例子。

| 表3-11

数据类型 | 占用字节数
Char | 1
Char * | 4
Short | 2
Int | 4（VC 6.0）2 (VC 1.5x)
Long | 4
Float | 4
Double | 8