Is there an integer data type that will always be exactly 2 bytes on 16-bit platforms, 4 bytes on 32-bit platforms, and 8 bytes on 64-bit platforms? Assume C++11, and that it would be used for calculations, not memory addressing.
There's std::size_t, but what's the signed equivalent (std::ptrdiff_t?), and is it guaranteed to fulfill the requirement?
There's std::intptr_t and std::uintptr_t, but they won't always be the same size as size_t.
There's std::int_leastN_t and std::int_fastN_t, but is either guaranteed to fulfill the requirement, and if so, what is the proper value of 'N'?
Does Boost provide anything like a(n) int_native_t and uint_native_t?
The problem with the question is that it's not at all clear how a term such as "16-bit" or "32-bit", which typically arises from what is essentially a CPU implementation detail, translates to user space.
For example, Z80-based 8-bit machines had both 8-bit and 16-bit registers and addressed memory with 16 bits, so their C implementations made int
16 bits wide. 16-bit machines (Amiga, Atari ST) had 32-bit registers or used segments to address more than 64k of memory (80286). Amiga C compilers from different manufacturers implemented different width of int
, and there was no accepted "native" int
.
The point is not that you can't rely on int
or long
to tell you the "size" of an architecture - that is the premise of your question - but that the architecture width is in fact irrelevant for a C implementation. When writing C code, you shouldn't care about the width of your bus, or the number of bits the processor internally grabs at once. (If you really need to care about that, you're likely writing non-portable low-level code to begin with and would get little benefit from portable type declarations.)
What you should care about are things like the largest memory location you can address and whether it fits in an integer type, the size of the difference of two pointers or the size of the maximum array index, and so on. You might also care about width of types that interface to the system, such as the largest time period since epoch you can represent, or the largest index into the file you can address. You get all of these by tuning into the standard C types such as intptr_t
, ptrdiff_t
, size_t
, time_t
, off_t
, and others — this is what they're for.
The short answer is no.
The closest is probably int
which the standard says "...has the natural size suggested by the architecture of the execution environment..." That's somewhat vague and basically unenforceable though. Just for example, a number of 64-bit compilers still use 32 bits for int
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With