Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: cast int to size_t

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];
}
like image 693
Uyghur Lives Matter Avatar asked Mar 30 '11 01:03

Uyghur Lives Matter


2 Answers

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

like image 158
R.. GitHub STOP HELPING ICE Avatar answered Sep 18 '22 18:09

R.. GitHub STOP HELPING ICE


size_t key_index = (size_t)hash(key) % size;

is fine. You actually don't even need the cast:

size_t key_index = hash(key) % size;

does the same thing.

like image 21
Stephen Canon Avatar answered Sep 17 '22 18:09

Stephen Canon