I'm looking for detailed information regarding the size of basic C++ types. I know that it depends on the architecture (16 bits, 32 bits, 64 bits) and the compiler.
But are there any standards for C++?
I'm using Visual Studio 2008 on a 32-bit architecture. Here is what I get:
char : 1 byte
short : 2 bytes
int : 4 bytes
long : 4 bytes
float : 4 bytes
double: 8 bytes
I tried to find, without much success, reliable information stating the sizes of char
, short
, int
, long
, double
, float
(and other types I didn't think of) under different architectures and compilers.
If you need fixed size types, use types like uint32_t (unsigned integer 32 bits) defined in stdint.h. They are specified in C99.
As you mentioned - it largely depends upon the compiler and the platform. For this, check the ANSI standard, http://home.att.net/~jackklein/c/inttypes.html
Here is the one for the Microsoft compiler: Data Type Ranges.
You can use:
datatype = int
,long int
etc. You will be able to see the size for whichever datatype you type.We are allowed to define a synonym for the type so we can create our own "standard".
On a machine in which sizeof(int) == 4, we can define:
So when we transfer the code to a different machine where actually the size of long int is 4, we can just redefine the single occurrence of int.
In practice there's no such thing. Often you can expect
std::size_t
to represent the unsigned native integer size on current architecture. i.e. 16-bit, 32-bit or 64-bit but it isn't always the case as pointed out in the comments to this answer.As far as all the other built-in types go, it really depends on the compiler. Here's two excerpts taken from the current working draft of the latest C++ standard:
If you want to you can statically (compile-time) assert the sizeof these fundamental types. It will alert people to think about porting your code if the sizeof assumptions change.
Updated: C++11 brought the types from TR1 officially into the standard:
And the "sized" types from
<cstdint>
Plus you get:
These types represent the smallest integer types with at least the specified number of bits. Likewise there are the "fastest" integer types with at least the specified number of bits:
What "fast" means, if anything, is up to the implementation. It need not be the fastest for all purposes either.