我正在寻找关于基本c++类型大小的详细信息。 我知道这取决于架构(16位、32位、64位)和编译器。

但是c++有标准吗?

我在32位架构上使用Visual Studio 2008。以下是我得到的答案:

char  : 1 byte
short : 2 bytes
int   : 4 bytes
long  : 4 bytes
float : 4 bytes
double: 8 bytes

我试图在不同的架构和编译器下找到char、short、int、long、double、float(以及其他我没有想到的类型)的大小的可靠信息,但没有多大成功。


当前回答

如果你需要固定大小的类型,使用类型像uint32_t(32位无符号整数)定义在stdint.h。它们在C99中指定。

其他回答

对于浮点数有一个标准(IEEE754):浮点数是32位,双精度数是64位。这是一种硬件标准,而不是c++标准,所以编译器理论上可以定义float和double为其他大小,但在实践中,我从未见过使用任何不同的架构。

c++标准没有以字节为单位指定整型的大小,但它指定了它们必须能够容纳的最小范围。您可以从所需的范围推断出最小大小(以位为单位)。您可以从该值和CHAR_BIT宏的值推断出最小的字节大小,CHAR_BIT宏定义了字节中的位数(除了最晦涩的平台之外,在所有平台中它都是8,而且不能小于8)。

char的另一个限制是它的大小总是1字节,或CHAR_BIT位(因此得名)。

标准(第22页)要求的最小范围是:

MSDN上的数据类型范围:

signed char: -127 to 127 (note, not -128 to 127; this accommodates 1's-complement platforms) unsigned char: 0 to 255 "plain" char: -127 to 127 or 0 to 255 (depends on default char signedness) signed short: -32767 to 32767 unsigned short: 0 to 65535 signed int: -32767 to 32767 unsigned int: 0 to 65535 signed long: -2147483647 to 2147483647 unsigned long: 0 to 4294967295 signed long long: -9223372036854775807 to 9223372036854775807 unsigned long long: 0 to 18446744073709551615 A C++ (or C) implementation can define the size of a type in bytes sizeof(type) to any value, as long as

表达式sizeof(type) * CHAR_BIT计算为足够包含所需范围的比特数,并且 类型的顺序仍然有效(例如sizeof(int) <= sizeof(long))。 实际的特定于实现的范围可以在C或c++的header中找到(或者更好的是,在header中找到模板化的std::numeric_limits)。

例如,这是你如何找到int的最大范围:

C:

#include <limits.h>
const int min_int = INT_MIN;
const int max_int = INT_MAX;

C++:

#include <limits>
const int min_int = std::numeric_limits<int>::min();
const int max_int = std::numeric_limits<int>::max();

这是正确的,但是,你说的也对: Char: 1字节 短:2字节 Int: 4字节 Long: 4字节 浮点数:4字节 Double: 8字节

因为32位体系结构仍然是默认的,也是最常用的,并且自从前32位时代内存可用性较低以来,他们就一直保持这些标准大小,为了向后兼容和标准化,它保持不变。即使是64位系统也倾向于使用这些并进行扩展/修改。 更多信息请参考:

http://en.cppreference.com/w/cpp/language/types

在64位机器上:

int: 4
long: 8
long long: 8
void*: 8
size_t: 8

c++标准是这样说的:

3.9.1,§2:

There are five signed integer types : "signed char", "short int", "int", "long int", and "long long int". In this list, each type provides at least as much storage as those preceding it in the list. Plain ints have the natural size suggested by the architecture of the execution environment (44); the other signed integer types are provided to meet special needs. (44) that is, large enough to contain any value in the range of INT_MIN and INT_MAX, as defined in the header <climits>.

结论:这取决于您使用的是哪种体系结构。其他任何假设都是错误的。

你可以使用OpenGL、Qt等库提供的变量。

例如,Qt提供了qint8(保证在Qt支持的所有平台上都是8位的)、qint16、qint32、qint64、quint8、quint16、quint32、quint64等等。