无符号整数溢出不会"环绕"

hag*_*wal -1 c printf integer-overflow

我从Integer Overflow Wiki读取以下行:

无符号整数溢出导致数量减去模2的幂,这意味着无符号整数在溢出时"环绕".

我有下面的代码,我试图创建一个哈希函数,并得到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 != '\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;
}
Run Code Online (Sandbox Code Playgroud)

dbu*_*ush 5

您正在使用错误的格式说明符printf.对于一个unsigned int,你应该使用%u而不是%d.

此外,你应该返回一个unsigned int而不是一个int.