我正在寻找关于基本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(以及其他我没有想到的类型)的大小的可靠信息,但没有多大成功。
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>.
结论:这取决于您使用的是哪种体系结构。其他任何假设都是错误的。
对于32位系统,“事实上”的标准是ILP32——也就是说,int、long和pointer都是32位的量。
对于64位系统,主要的Unix“事实上”标准是LP64 -长和指针是64位(但int是32位)。Windows 64位标准是LLP64 - long long和pointer是64位(但long和int都是32位)。
曾经,一些Unix系统使用ILP64组织。
这些事实上的标准没有一个是由C标准(ISO/IEC 9899:1999)立法的,但都是被C标准所允许的。
并且,根据定义,sizeof(char)是1,尽管在Perl配置脚本中进行了测试。
注意,有些机器(Crays) CHAR_BIT远大于8。这意味着,IIRC sizeof(int)也是1,因为char和int都是32位的。
实际上没有这样的事情。通常,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。如果假设的大小发生变化,它会提醒人们考虑移植您的代码。