Reputation: 19762
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];
}
Upvotes: 18
Views: 83267
Reputation: 1546
Aside from the casting issue (which you don't need as stated before), there is some more intricate things that might go wrong with the code.
if hash()
is supposed to return an index to an array, it should return a size_t
as well. Since it doesn't, you might get weird effects when key_index
is larger than INT_MAX
.
I would say that size
, hash()
, key_index
should all be of the same type, probably size_t
to be sure, for example:
size_t hash(void * key) {
//...
}
int main (int argc, char * argv[]) {
size_t size = 10;
void * items[size];
//...
void * key = ...;
size_t key_index = hash(key) % size;
void * item = items[key_index];
}
Upvotes: 3
Reputation: 215173
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...
Upvotes: 19
Reputation: 106117
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.
Upvotes: 7