Is it good practice to use size_t in C++?

In your case don't use any of them. Either use a container and iterators or create a new data type (e.g. employee database) which offers iterator/range access.

As for unsigned, Bjarne Stroustrup wrote in TCPL:

The unsigned integer types are ideal for uses that treat storage as a bit array. Using an unsigned instead of an int to gain one more bit to represent positive integers is almost never a good idea. Attempts to ensure that some values are positive by declaring variables unsigned will typically be defeated by the implicit conversion rules.


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

Tags:

C++

Types