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]
}
Best Answer
size_t
may have different size toint
.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 ofint
, if your filesystem supports 64-bit files.Do realise that object sizes (as obtained by
sizeof
) are of typesize_t
, notint
orunsigned int
; also, correspondingly, there is aptrdiff_t
for the difference between two pointers (e.g.,&a[5] - &a[0] == ptrdiff_t(5)
).