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];
}
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:
Of course if you enable some ultra-picky warning levels, your implicit conversions might cause lots of warnings even when they're correct...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With