当使用任何编程语言编程,需要使用不同的变量来存储各种信息。变量是保留在内存位置用来存储值。这意味着,当创建一个变量,需要在内存中保留一些空间。
想要存储像字符的各种数据类型,宽字符,整数,浮点,双浮点,布尔等。基于一个变量的数据类型的信息,在操作系统中分配内存,并决定什么可以被存储在保留的内存。
原始的内置类型:
类型 | 关键字 |
---|---|
布尔 | bool |
字符 | char |
整型 | int |
浮点 | float |
双浮点 | double |
无值 | void |
宽字符 | wchar_t |
几种的基本类型可以使用一种这些类型的修饰符或多个被修改:
-
signed
-
unsigned
-
short
-
long
类型 | 典型位宽 | 典型范围 |
---|---|---|
char | 1byte | -127 to 127 or 0 to 255 |
unsigned char | 1byte | 0 to 255 |
signed char | 1byte | -127 to 127 |
int | 4bytes | -2147483648 to 2147483647 |
unsigned int | 4bytes | 0 to 4294967295 |
signed int | 4bytes | -2147483648 to 2147483647 |
short int | 2bytes | -32768 to 32767 |
unsigned short int | Range | 0 to 65,535 |
signed short int | Range | -32768 to 32767 |
long int | 4bytes | -2,147,483,647 to 2,147,483,647 |
signed long int | 4bytes | same as long int |
unsigned long int | 4bytes | 0 to 4,294,967,295 |
float | 4bytes | +/- 3.4e +/- 38 (~7 digits) |
double | 8bytes | +/- 1.7e +/- 308 (~15 digits) |
long double | 8bytes | +/- 1.7e +/- 308 (~15 digits) |
wchar_t | 2 or 4 bytes | 1 wide character |
变量的大小如上表显示,这取决于编译器和正在使用的计算机而不同。
下面是一个例子,这将产生的各种数据类型的正确大小的计算机上。
#include<iostream>
using namespace std;
int main()
{
cout<<"sizeof(char)="<<sizeof(char)<<endl;
cout<<"sizeof(unsigned char)="<<sizeof(unsigned char)<<endl;
cout<<"sizeof(signed char)="<<sizeof(signed char)<<endl;
cout<<"sizeof(int)="<<sizeof(int)<<endl;
cout<<"sizeof(unsigned int)="<<sizeof(unsigned int)<<endl;
cout<<"sizeof(signed int)="<<sizeof(signed int)<<endl;
cout<<"sizeof(short int)="<<sizeof(short int)<<endl;
cout<<"sizeof(unsigned short int)="<<sizeof(unsigned short int)<<endl;
cout<<"sizeof(signed short int)="<<sizeof(signed short int)<<endl;
cout<<"sizeof(long int)="<<sizeof(long int)<<endl;
cout<<"sizeof(signed long int)="<<sizeof(signed long int)<<endl;
cout<<"sizeof(unsigned long intt)="<<sizeof(unsigned long int)<<endl;
cout<<"sizeof(float)="<<sizeof(float)<<endl;
cout<<"sizeof(double)="<<sizeof(double)<<endl;
cout<<"sizeof(long double)="<<sizeof(long double)<<endl;
cout<<"sizeof(unsigned long int)="<<sizeof(unsigned long int)<<endl;
cout<<"sizeof(wchar_t)="<<sizeof(wchar_t)<<endl;
return 0;
}
typedef声明:
可以创建一个新的名称为现有类型使用typedef。以下是简单的语法使用的typedef来定义新类型:
typedef type newname;
例如,下面告诉编译器,feet是另一个int名字:
typedef int feet;
现在,下面的声明是完全合法的,并创建一个整型变量称为distance:
feet distance;
枚举类型:
枚举类型声明的可选类型名和一组零个或多个标识符可以被用作类型的值。每个枚举是一个常量,其类型是枚举。
要创建一个枚举需要使用关键字enum。枚举类型的一般形式是:
enum enum-name { list of names } var-list;
在这里,enum-name是枚举的类型名称。名称的列表以逗号分隔。
例如,下面的代码定义的颜色称为colors枚举和c型颜色的变量。最后,c的分配值为“blue”。
enum color { red, green, blue } c; c = blue;
缺省情况下,第一个名字的值是0,第二个名字的值为1,第三的值为2,依此类推。但是可以通过添加一个初始化给出一个名称的特定值。例如,在下面列举,green的值为5。
enum color { red, green=5, blue };
这里,blue 的值为6,因为每个名字会比它前面的值大1。
#include<iostream>
using namespace std;
typedef int fxl;
enum color{red,green,yellow};
int main()
{
cout<<"sizeof(fxl)="<<sizeof(fxl)<<endl;
color a;
a=red;
cout<<"a="<<a<<endl;
return 0;
}