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

As a newbie, I'm really confused about size_t . I can use int , float or other types. Why else declare the type size_t . I do not feel its advantages. I have looked through several pages , but I still cannot understand it.

+6
source share
3 answers

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

size_t literally defined as large enough to represent the size of any object on your platform. Others do not. So, when you want to keep the size of an object, why do you use anything else?

You can use int if you want, but you will deliberately choose a lower option that leads to errors. I donโ€™t quite understand why you want to do this, but hey your code.

If you decide to use float , please tell us which program you are writing so that we can avoid it. :)

+17
source

Using a float would be horrible, as that would be the wrong use of floating point types, plus type advancement would mean that multiplying the size of something would take place in the floating point!

Using a int also be horrible, since the int specification is intentionally freely defined by the C ++ standard. (It can be like 16 bits).

But the size_t type is guaranteed to adequately display the size of almost any size and, of course, the size of the containers in the C ++ standard library. Its specific details depend on the specific platform and architecture. The fact that this is an unsigned type is the subject of much discussion. (I personally think that it was a mistake to make it unsigned , as this can ruin the code using relational operators and introduce fatal errors that are difficult to detect).

+4
source

I would advise you to use size_t when you want to store the sizes of classes or structures or when you work with raw memory (for example, save the size of raw memory or use the raw array as an index). However, for indexing / iteration over standard containers (e.g. std :: vector), I recommend using the base size type of this container (e.g. vector :: size_type).

0
source

All Articles