I am so confused about size_t
. I have searched on the internet and everywhere mentioned that size_t
is an unsigned type so, it can represent only non-negative values.
My first question is: if it is used to represent only non-negative values, why don't we use unsigned int
instead of size_t
?
My second question is: are size_t
and unsigned int
interchangeable or not? If not, then why?
And can anyone give me a good example of size_t
and briefly its workings?
Best Answer
Because
unsigned int
is not the only unsigned integer type.size_t
could be any ofunsigned char
,unsigned short
,unsigned int
,unsigned long
orunsigned long long
, depending on the implementation.They aren't interchangeable, for the reason explained above
^^
.I don't quite get what you mean by "its brief working". It works like any other unsigned type (in particular, like the type it's typedeffed to). You are encouraged to use
size_t
when you are describing the size of an object. In particular, thesizeof
operator and various standard library functions, such asstrlen()
, returnsize_t
.Bonus: here's a good article about
size_t
(and the closely relatedptrdiff_t
type). It reasons very well why you should use it.