I have been seeing a lot of people lately say that you should use size_t instead of int. But what is the difference? Is it always better? Or are there situations for int, and situations for size_t? Or maybe size_t is similar to long? When should I use int, when should I use size_t, and when should I use long?
int vs size_t vs long
124 Views Asked by Harr AtThere are 2 best solutions below
On
The main reason is self-documenting code. size_t is used exclusively for the purpose of describing the size of things.
But there are also some practical advantages of using size_t over int:
Array/object sizes are always unsigned and positive and should therefore be represented by an unsigned type. Using a negative value as array size is always a bug. Using a negative value as array index is also problematic since it is hard to read, probably also a bug.
intmay overflow in certain scenarios when it is not large enough to contain a requested size.size_tis guaranteed to be at least large enough to contain the size of the largest supported object.intmay be subject to implicit promotion in case it is mixed with larger operands in the same expression.intis further problematic if used to represent addresses, or if used to store the results of pointer arithmetic. Here there are other more suitable types likeuintptr_tandptrdiff_trespectively.
size_t therefore provides better compatibility with the sizeof operator as well as various standard library functions (like for example strlen). Mostly these problems get exposed when porting sloppily written code using int into 64 bit systems.
However size_t is not without problems either, since its size is unknown. In certain scenarios like hardware-related programming, the fixed width types in stdint.h might be more suitable to use than size_t, or you might risk getting a type that is too large.
Some old C libs also had bad compliance and weren't properly supporting %zu for the printf/scanf family of functions.
Usually
intmath may fail size calculation that woks withsize_tmath.intrange may be (and often is) less thansize_trange.When
sizeof some_objectexceedsINT_MAX, following code will certainly lead to errors.unsignedrange may be less thansize_trange.String lengths may be longer than
UINT_MAXsize_tis an unsigned type, so avoid tests likesize >= 0,size < 0,size == -1.When code decrements the size below zero, we have issues.
Instead re-work code in some fashion.