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?
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.
The type size_t is an unsigned type capable of representing all possible results of sizeof and _Alignof operators.
See https://port70.net/~nsz/c/c11/n1570.html#6.5.3.4p5
The unsigned int is an unsigned variant of ... int that can represent integers from 0 to 65535. It may be capable of representing larger integers.
See https://port70.net/~nsz/c/c11/n1570.html#5.2.4.2.1
They may or may not be the same type. On modern 64-bit machines they are not.