Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to use `size_t` in C++?

As a beginner, I'm really confused about size_t. I can use int, float or other types. Why still declare size_t type. I don't feel its advantages. I've viewed some pages, but I still can't understand it.

like image 898
kevin4z Avatar asked May 11 '16 09:05

kevin4z


People also ask

Why do we use Size_t in C?

size_t is the result type of the sizeof operator. Use size_t for variables that model size or index in an array. size_t conveys semantics: you immediately know it represents a size in bytes or an index, rather than just another integer. Also, using size_t to represent a size in bytes helps making the code portable.

Should I always use Size_t?

size_t is an unsigned integer that is capable of holding the size of the largest object you can allocate. It is useful for indexing because this means it can index into the largest array you can allocate. This does not mean it is required or even necessarily recommended for indexing.

Should I use Size_t instead of int?

When writing C code you should always use size_t whenever dealing with memory ranges. The int type on the other hand is basically defined as the size of the (signed) integer value that the host machine can use to most efficiently perform integer arithmetic.

Is Size_t always unsigned int?

No. size_t can and does differ from unsigned int .


2 Answers

Its main advantage is that it's the right tool for the job.

size_t is literally defined to be big enough to represent the size of any object on your platform. The others are not. So, when you want to store the size of an object, why would you use anything else?

You can use int if you like, but you'll be deliberately choosing the inferior option that leads to bugs. I don't quite understand why you'd want to do so, but hey it's your code.

If you choose to use float, though, please tell us what program you're writing so we can avoid it. :)

like image 139
Lightness Races in Orbit Avatar answered Oct 08 '22 03:10

Lightness Races in Orbit


Using a float would be horrible since that would be a misuse of floating point types, plus type promotion would mean that multiplying the size of anything would take place in floating point!

Using a int would also be horrible since the specifics of an int are intentionally loosely defined by the C++ standard. (It could be as small as 16 bits).

But a size_t type is guaranteed to adequately represent the size of pretty much anything and certainly the sizes of containers in the C++ standard library. Its specific details are dependent on a particular platform and architecture. The fact that it's an unsigned type is the subject of much debate. (I personally believe it was a mistake to make it unsigned as it can mess up code using relational operators and introduce pernicious bugs that are difficult to spot).

like image 20
Bathsheba Avatar answered Oct 08 '22 03:10

Bathsheba