Why should we use size_t in C? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why should we use size_t in C?

Why can't we just use an int or an unsigned short to store the size of a variable? Is it used just to improve the readability of the code?

14th May 2021, 8:13 AM
Calvin Thomas
Calvin Thomas - avatar
3 Answers
+ 4
size_t is typedef for unsigned int. Contrary to few answers mentioned here it is heavily used in C++ especially in C++ Standard Template Library (STL). It's main purpose is to represent values that sementically cannot be / should not be negative for example length of a string or sizeof an array etc. A negative string length or negative size of an array makes no sense. Use of signed ints for these purposes indicates the values can go negative, although they may never. - ~ swim ~ These posts might help you more. https://www.sololearn.com/discuss/1923033/?ref=app https://www.sololearn.com/discuss/2156436/?ref=app https://www.sololearn.com/discuss/2262518/?ref=app https://www.sololearn.com/discuss/974838/?ref=app https://www.sololearn.com/discuss/2096677/?ref=app https://www.sololearn.com/discuss/2671702/?ref=app https://www.sololearn.com/discuss/2350252/?ref=app
14th May 2021, 8:41 AM
Rohit
+ 1
Hey Calvin Thomas size_t is an unsigned type. So, it cannot represent any negative values. You can use it when you are counting something, and are sure that it cannot be negative.😀
14th May 2021, 9:00 AM
Giriraj Yalpalwar
Giriraj Yalpalwar - avatar
+ 1
rkk and Thirt13n Thanks a lot!
14th May 2021, 12:33 PM
Calvin Thomas
Calvin Thomas - avatar