Why does size_t exist in C / C ++ and can / should be replaced?

I am an electrical engineer turned to a computer scientist. It is very difficult for me to understand why in C ++ there are so many things that are almost the same but not completely the same. Example: short vs int vs unsigned int vs size_t vs long int vs long long int vs uint8_t (I don't know if there is any additional way to assign an integer). This seems to make the language unnecessarily complex.

Can or should size_t be replaced or does it have any function that cannot be used in any other way?


[EDIT]

After the helpful answers, there is something that I still don’t see. size_t is useful in terms of portability and performance, as suggested by several people. But how useful it is, is there a quantitative way or numerical data to evaluate the benefits that exceed only int and fire all your brothers.

+7
c ++ c programming-languages size-t typing
source share
2 answers

std::size_t is a typedef for the underlying unsigned type, and it should be able to represent any possible index / size in your program (technically this is also the result of the sizeof operator). Its base type may vary in different implementations, and since you want portability, you use std::size_t and don't care if it is unsigned long int or unsigned long long int , etc.

std::size_t does not use any function that cannot be used in any other way, it is just a convenient type alias and nothing more.

In response to editing the OP

@HoapHumanoid. Editing is not a good question for StackOverflow, as it is a matter of personal interpretation / preference. Of course, you can have only one type of numeric type or a type of fixed size, however, when you want to squeeze out as much performance from your processor that you have to have a lot, each of which is able to display a certain range, depending on the physical . Since computer architectures vary widely, each architecture will impose its own size, for example. int , long , etc. When you combine this problem with portability, then size_t occurs naturally. What else would you use in a common function, for example, is it a guarantee of the maximum possible amount of memory for each possible implementation ? Do you use int byte count? Or maybe long int ? You need to read the compiler manual, check the appropriate type, etc., and then use it. What the C ++ implementation does for you defines the appropriate type.

+14
source share

You forgot long long int , most unsigned versions, uint8_t and friends, and maybe a little more. uint8_t

Some languages ​​fix the size of integer types. C ++ is not one of them; the programmer is given a lot of flexibility to balance performance across size and range.

But size_t extremely useful. The ability to store the size of any object or any valid array index is guaranteed. Without this, it would be much more difficult to write portable but effective programs.

+2
source share

All Articles