I've got an impression that size_t
is unsigned int
. But can I just write unsigned int
instead of size_t
in my code?
size_t
is the most correct type to use when describing the sizes of arrays and objects. It's guaranteed to be unsigned and is supposedly "large enough" to hold any object size for the given system. Therefore it is more portable to use for that purpose than unsigned int
, which is in practice either 16 or 32 bits on all common computers.
So the most canonical form of a for
loop when iterating over an array is actually:
for(size_t i=0; i<sizeof array/sizeof *array; i++)
{
do_something(array[i]);
}
And not int i=0;
which is perhaps more commonly seen even in some C books.
size_t
is also the type returned from the sizeof
operator. Using the right type might matter in some situations, for example printf("%u", sizeof obj);
is formally undefined behavior, so it might in theory crash printf or print gibberish. You have to use %zu
for size_t
.
It is quite possible that size_t
happens to be the very same type as unsigned long
or unsigned long long
or uint32_t
or uint64_t
though.
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