我正在寻找关于基本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(以及其他我没有想到的类型)的大小的可靠信息,但没有多大成功。
当涉及到不同架构和不同编译器的内置类型时,只需在你的架构上用编译器运行以下代码,看看它输出了什么。下面是我的Ubuntu 13.04 (Raring Ringtail) 64位g++4.7.3输出。还请注意下面的回答,这就是为什么输出是这样排序的:
有五种标准的有符号整型:有符号char、short int、int、long int和long long int。在此列表中,每种类型提供的存储空间至少与列表中前面的类型相同。”
#include <iostream>
int main ( int argc, char * argv[] )
{
std::cout<< "size of char: " << sizeof (char) << std::endl;
std::cout<< "size of short: " << sizeof (short) << std::endl;
std::cout<< "size of int: " << sizeof (int) << std::endl;
std::cout<< "size of long: " << sizeof (long) << std::endl;
std::cout<< "size of long long: " << sizeof (long long) << std::endl;
std::cout<< "size of float: " << sizeof (float) << std::endl;
std::cout<< "size of double: " << sizeof (double) << std::endl;
std::cout<< "size of pointer: " << sizeof (int *) << std::endl;
}
size of char: 1
size of short: 2
size of int: 4
size of long: 8
size of long long: 8
size of float: 4
size of double: 8
size of pointer: 8
对于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位的。
有标准。
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位,以此类推。
更新:c++ 11将TR1中的类型正式引入标准:
Long Long int
Unsigned long long int
以及<cstdint>中的"size "类型
int8_t
int16_t
int32_t
int64_t
(以及未签名的副本)。
另外,你会得到:
int_least8_t
int_least16_t
int_least32_t
int_least64_t
加上未签名的对应项。
这些类型表示至少具有指定位数的最小整数类型。同样,也有“最快”的整数类型,至少具有指定的比特数:
int_fast8_t
int_fast16_t
int_fast32_t
int_fast64_t
加上无符号的版本。
“快”意味着什么,如果有的话,取决于实现。它也不需要在所有方面都是最快的。
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>.
结论:这取决于您使用的是哪种体系结构。其他任何假设都是错误的。