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?
Is it (
size_t
) always better?
Usually
int
math may fail size calculation that woks with size_t
math. int r = rand();
int c = rand();
char *ptr1 = malloc(r * c); // Overflow possible
char *ptr2 = malloc((size_t) 1 * r*c); // Overflow possible, yet less likely.
int
range may be (and often is) less than size_t
range.When sizeof some_object
exceeds INT_MAX
, following code will certainly lead to errors.
int sz = sizeof some_object; // Problem when size is large.
// Good as
size_t sz = sizeof some_object; // No problem for all sizeof return values.
unsigned
range may be less than size_t
range.String lengths may be longer than UINT_MAX
unsigned sz = strlen(pointer_to_a_string); // Problem when length is large.
// Good as
size_t sz = strlen(pointer_to_a_string); // No problem for all values from strlen().
size_t
is an unsigned type, so avoid tests like size >= 0
, size < 0
, size == -1
.When code decrements the size below zero, we have issues.
// Compare
int isize = sizeof object; // Bad as size may exceed INT_MAX
while (isize >= 0) {
...
isize--;
}
size_t usize = sizeof object;
while (usize >= 0) { // Bad as usize >= 0 is _always_ true
...
usize--;
}
Instead re-work code in some fashion.
size_t usize = sizeof object;
do {
...
} while (usize-- > 0):