C: cast int to size_t

All Workers Are Essential picture All Workers Are Essential · Mar 30, 2011 · Viewed 57.9k times · Source

What is the proper way to convert/cast an int to a size_t in C99 on both 32bit and 64bit linux platforms?

Example:

int hash(void * key) {
    //...
}

int main (int argc, char * argv[]) {
    size_t size = 10;
    void * items[size];
    //...
    void * key = ...;
    // Is this the right way to convert the returned int from the hash function
    // to a size_t?
    size_t key_index = (size_t)hash(key) % size;
    void * item = items[key_index];
}

Answer

R.. GitHub STOP HELPING ICE picture R.. GitHub STOP HELPING ICE · Mar 30, 2011

All arithmetic types convert implicitly in C. It's very rare that you need a cast - usually only when you want to convert down, reducing modulo 1 plus the max value of the smaller type, or when you need to force arithmetic into unsigned mode to use the properties of unsigned arithmetic.

Personally, I dislike seeing casts because:

  1. They're ugly visual clutter, and
  2. They suggest to me that the person who wrote the code was getting warnings about types, and threw in casts to shut up the compiler without understanding the reason for the warnings.

Of course if you enable some ultra-picky warning levels, your implicit conversions might cause lots of warnings even when they're correct...