C++ Best Practices – Using size_t

c++types

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 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)).