Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I just use unsigned int instead of size_t? [duplicate]

Tags:

c

unsigned

size-t

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?

like image 314
stardustd Avatar asked Dec 18 '22 11:12

stardustd


1 Answers

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.

like image 110
Lundin Avatar answered Dec 31 '22 01:12

Lundin