我正在寻找关于基本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(以及其他我没有想到的类型)的大小的可靠信息,但没有多大成功。
实际上没有这样的事情。通常,std::size_t表示当前体系结构上的无符号本机整数大小。即16位、32位或64位,但并不总是如此,就像这个答案的评论中指出的那样。
至于所有其他内置类型,它实际上取决于编译器。以下是摘自最新c++标准的当前工作草案的两段摘录:
There are five standard 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.
For each of the standard signed integer types, there exists a corresponding (but different) standard unsigned integer type: unsigned char, unsigned short int, unsigned int, unsigned long int, and unsigned long long int, each of which occupies the same amount of storage and has the same alignment requirements.
如果您愿意,您可以静态(编译时)断言这些基本类型的sizeof。如果假设的大小发生变化,它会提醒人们考虑移植您的代码。
有标准。
C90标准要求
sizeof(short) <= sizeof(int) <= sizeof(long)
C99标准要求
sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long)
这是C99的规格。第22页详细介绍了不同整型的大小。
下面是Windows平台的int类型大小(位):
Type C99 Minimum Windows 32bit
char 8 8
short 16 16
int 16 32
long 32 32
long long 64 64
如果你关心可移植性,或者你想要类型的名称反映大小,你可以查看头文件<inttypes.h>,其中有以下宏:
int8_t
int16_t
int32_t
int64_t
Int8_t保证为8位,int16_t保证为16位,以此类推。
我们可以为类型定义同义词,这样我们就可以创建自己的“标准”。
在sizeof(int) == 4的机器上,我们可以定义:
typedef int int32;
int32 i;
int32 j;
...
所以当我们把代码转移到另一台机器上,当long int的大小是4时,我们可以重新定义int的一次出现。
typedef long int int32;
int32 i;
int32 j;
...
有一个标准,它是在各种标准文档(ISO, ANSI等)中指定的。
维基百科有一个很好的页面解释了各种类型和它们可以存储的最大值:
计算机科学中的整数。
然而,即使使用标准的c++编译器,您也可以使用以下代码片段相对容易地找到:
#include <iostream>
#include <limits>
int main() {
// Change the template parameter to the various different types.
std::cout << std::numeric_limits<int>::max() << std::endl;
}
std::numeric_limits的文档可以在Roguewave上找到。它包含大量其他命令,您可以调用这些命令来查找各种限制。这可以用于任何传递大小的任意类型,例如std::streamsize。
约翰的回答包含了最好的描述,因为那些肯定是成立的。不管你在什么平台上,有另一个很好的页面详细介绍了每种类型必须包含多少位:int类型,这是在标准中定义的。
我希望这能有所帮助!