无符号整数不会溢出 "wrap around"

Unsigned integers overflow does not "wrap around"

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

我在下面的代码中尝试创建哈希函数并遇到了 int 溢出情况。我试图通过使用 unsigned int 来缓解它,但它没有用,我能够看到负值。

我知道我可以用其他方式处理它并且它有效,如我的代码注释中所示 - Comment 2:。但这是正确的方法吗?为什么 unsigned int 没有环绕和溢出?

int hash(char *word) {
    char *temp = word;
    unsigned int hash = 0; // Comment 1: I tried to handle int overflow using "unsigned" int.
    while (*word != '[=11=]') {
        // 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;
}

您为 printf 使用了错误的格式说明符。对于 unsigned int,您应该使用 %u 而不是 %d

此外,您应该返回 unsigned int 而不是 int