I read following line from Integer Overflow Wiki:
while unsigned integer overflow causes the number to be reduced modulo a power of two, meaning that unsigned integers "wrap around" on overflow.
I have below code where I am trying to create a hash function and got int overflow situation. I tried to mitigate it by using unsigned int
but it didn't work and I was able to see negative values.
I know I can handle it other way and it works, as shown in my code comment - Comment 2:
. But is it right way and why unsigned int
was not wrapping around and overflowing?
int hash(char *word) {
char *temp = word;
unsigned int hash = 0; // Comment 1: I tried to handle int overflow using "unsigned" int.
while (*word != '\0') {
// Comment 2: This works but I do not want to go this way.
//while ((hash * PRIME_MULTIPLIER) < 0) {
// hash = (hash * PRIME_MULTIPLIER) + 2147483647;
//}
hash = hash * PRIME_MULTIPLIER + *word;
word++;
}
printf("Hash for %s is %d\n", temp, hash);
return hash;
}