Is sizeof(size_t)==8
the equivalent of saying that the platform is 64-bits ?
Conversely, is sizeof(size_t)==4
the equivalent of saying that the platform is 32-bits ?
More importantly, is this test safe and reliable under all circumstances, keeping in mind OS and compilers portability ? Are there some weird corner-cases, including potential situations where size_t
might be missing ?
I'm a bit worried that size_t
might only be guaranteed for C99 environments.
size_t type is a base unsigned integer type of C/C++ language. It is the type of the result returned by sizeof operator. The type's size is chosen so that it can store the maximum size of a theoretically possible array of any type. On a 32-bit system size_t will take 32 bits, on a 64-bit one 64 bits.
uint64_t can easier be greater than size_t . But it is quite possible that you might have to work with integer values that don't fit into uint64_t . std::malloc and std::allocator also use std::size_t .
Practically speaking, yes, this is safe and reliable. Platforms you are likely to target or ever target in the future are all byte-addressable, with 8-bit bytes and size_t
equal to the machine word length. Most platforms provide guarantees that this will continue to be the case indefinitely (POSIX guarantees this, for example).
Theoretically speaking, no, this is not safe and reliable. Obscure systems like the Cray-1, the PDP-10, and various DSP systems will trip you up. However, consider this: what are the chances that you would ever design software for a Cray-1, which was obsolete before that junior engineer sitting next to you was born?
size_t
is a data type that is able to represent the size of any object.
64-bits usually refers to the fact that 64 bits are available to address virtual memory. In C, memory is addressed using pointers. As such, sizeof(void*)
seems to be more adequate to test for 64-bit environment.
However, this is not guaranteed by the C standard. There might be obscure cases where no safe and reliable way to determine the hardware architecture using C exists.
Because sizeof
returns the size as multiples of the size of a char
, you might want to look at CHAR_BIT
(defined in limits.h) to see how many bits there are in a char.
More importantly, is this test safe and reliable under all circumstances, keeping in mind OS and compilers portability ?
There is no "portable way" to do this, because C standard let the environment define SIZE_MAX
as large as he wants (as long as it is greater than 65535
). But C standard doesn't define what are "32 bits" and "64 bits" platforms neither.
However, on common memory models, size_t
is 32 bits on 32 bits platforms and 64 bits on 64 bits platforms.
I'm a bit worried that
size_t
might only be guaranteed for C99 environments.
size_t
is in C89 too. So, as long as your environment is standard, it should define size_t
.
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