cintegerlong-integersize-t

int vs size_t vs long


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?


Solution

  • Is it (size_t) always better?

    Usually


        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.
    

    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.
    

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

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