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.
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.
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.
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.
No. size_t can and does differ from unsigned int .
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. :)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With