int hash (const string &key, int tableSize) {
int hashVal = 0;
for (int i = 0; i < key.length(); i++)
hashVal = 37*hashVal + key[i];
hashVal %= tableSize;
if (hashVal < 0) /* in case overflows occurs */
hashVal += tableSize;
return hashVal;
};
Why do we control if hashVal is smaller than zero? How is this possible?
If the string is long enough, the code:
might cause the value of
hashValto exceed the maximum value of anint(typically something like 231 − 1) and become negative. This is known as integer overflow.The C++ standard does not specify whether the value of the
%operator for negative operands should be positive or negative; thus, depending on your compiler and CPU architecture (and possibly compile-time switches), an expression like-47 % 37may evaluate to either-10or27. Thus, the code you’ve quoted guards against the former possibility by adding the modulus to the result if it’s negative.By the way, an easier way to avoid this issue would have been to define
hashValas unsigned.