I've seen people use size_t
whenever they mean an unsigned integer. For example:
class Company {
size_t num_employees_;
// ...
};
Is that good practice? One thing is you have to include <cstddef>
. Should it be unsigned int
instead? Or even just int
?
Just using int
sounds attractive to me since it avoids stupid bugs like these (because people do often use int
):
for(int i = num_employees_ - 1; i >= 0; --i) {
// do something with employee_[i]
}
Using size_t appropriately can improve the portability, efficiency, or readability of your code. Maybe even all three. Numerous functions in the Standard C library accept arguments or return values that represent object sizes in bytes.
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.
size_t type is a base unsigned integer type of C/C++ language. It is the type of the result returned by sizeof operator. The type's size is chosen so that it can store the maximum size of a theoretically possible array of any type. On a 32-bit system size_t will take 32 bits, on a 64-bit one 64 bits.
So yeah, both are same; the only difference is that C++ defines size_t in std namespace.
size_t
may have different size to int
.
For things like number of employees, etc., this difference usually is inconsequential; how often does one have more than 2^32 employees? However, if you a field to represent a file size, you will want to use size_t
instead of int
, if your filesystem supports 64-bit files.
Do realise that object sizes (as obtained by sizeof
) are of type size_t
, not int
or unsigned int
; also, correspondingly, there is a ptrdiff_t
for the difference between two pointers (e.g., &a[5] - &a[0] == ptrdiff_t(5)
).
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