所有变量在声明时都使用 data-type 来限制要存储的数据类型。因此,我们可以说数据类型是用来告诉变量它可以存储的数据类型。每当在 C++ 中定义变量时,编译器都会根据声明变量的数据类型为该变量分配一些内存。每种数据类型需要不同数量的内存。
C++中的数据类型主要分为三种:
C++ 中可用的数据类型修饰符有:
注意:以上值可能因编译器而异。在上面的例子中,我们考虑了 GCC 32 位。
我们可以通过使用 sizeof() 运算符并将数据类型的关键字作为参数传递给该函数来显示所有数据类型的大小,如下所示:
输出:

- 原始数据类型:这些数据类型是内置或预定义的数据类型,用户可以直接使用来声明变量。例如:int、char、float、bool 等。C++ 中可用的原始数据类型有:
- Integer
- Character
- Boolean
- Floating Point
- Double Floating Point
- Valueless or Void
- Wide Character
- 派生数据类型:从原始或内置数据类型派生的数据类型称为派生数据类型。这些可以有四种类型,即:
- Function
- Array
- Pointer
- Reference
- 抽象或用户定义的数据类型:这些数据类型由用户自己定义。比如,在 C++ 中定义一个类或一个结构。C++ 提供以下用户定义的数据类型:
- Class
- Structure
- Union
- Enumeration
- Typedef defined DataType
- Integer:用于整数数据类型的关键字是int。整数通常需要 4 个字节的内存空间,范围从 -2147483648 到 2147483647。
- Character:字符数据类型用于存储字符。用于字符数据类型的关键字是char。字符通常需要 1 个字节的内存空间,范围从 -128 到 127 或 0 到 255。
- Boolean:布尔数据类型用于存储布尔值或逻辑值。布尔变量可以存储true或false。用于布尔数据类型的关键字是bool。
- Floating Point:浮点数据类型用于存储单精度浮点值或十进制值。用于浮点数据类型的关键字是float。浮点变量通常需要 4 字节的内存空间。
- Double Floating Point:双浮点数据类型用于存储双精度浮点值或十进制值。用于双浮点数据类型的关键字是double。双变量通常需要 8 字节的内存空间。
- void : void 表示没有任何价值。void 数据类型表示无价值的实体。void 数据类型用于那些不返回值的函数。
- Wide character:宽字符数据类型也是字符数据类型,但该数据类型的大小大于普通的 8 位数据类型。由wchar_t表示。它通常为 2 或 4 个字节长。

- Signed
- Unsigned
- Short
- Long
数据类型 | 大小(字节) | 范围 |
---|---|---|
short int | 2 | -32,768 to 32,767 |
unsigned short int | 2 | 0 to 65,535 |
unsigned int | 4 | 0 to 4,294,967,295 |
int | 4 | -2,147,483,648 to 2,147,483,647 |
long int | 4 | -2,147,483,648 to 2,147,483,647 |
unsigned long int | 4 | 0 to 4,294,967,295 |
long long int | 8 | -(2^63) to (2^63)-1 |
unsigned long long int | 8 | 0 to 18,446,744,073,709,551,615 |
signed char | 1 | -128 to 127 |
unsigned char | 1 | 0 to 255 |
float | 4 | |
double | 8 | |
long double | 12 | |
wchar_t | 2 or 4 | 1 wide character |
// C++ program to sizes of data types
#include<iostream>
using namespace std;
int main()
{
cout << "Size of char : " << sizeof(char)
<< " byte" << endl;
cout << "Size of int : " << sizeof(int)
<< " bytes" << endl;
cout << "Size of short int : " << sizeof(short int)
<< " bytes" << endl;
cout << "Size of long int : " << sizeof(long int)
<< " bytes" << endl;
cout << "Size of signed long int : " << sizeof(signed long int)
<< " bytes" << endl;
cout << "Size of unsigned long int : " << sizeof(unsigned long int)
<< " bytes" << endl;
cout << "Size of float : " << sizeof(float)
<< " bytes" <<endl;
cout << "Size of double : " << sizeof(double)
<< " bytes" << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t)
<< " bytes" <<endl;
return 0;
}
Size of char : 1 byte Size of int : 4 bytes Size of short int : 2 bytes Size of long int : 8 bytes Size of signed long int : 8 bytes Size of unsigned long int : 8 bytes Size of float : 4 bytes Size of double : 8 bytes Size of wchar_t : 4 bytes