Is there any difference between 1U and 1 in C?

后端 未结 4 1032
别跟我提以往
别跟我提以往 2020-12-28 16:51
    while ((1U << i) < nSize) {
        i++;
    }

Any particular reason to use 1U instead of 1?

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-28 17:11

    If nSize is an int, it can be maximum of 2147483647 (2^31-1). If you use 1 instead of 1U then 1 << 30 will get you 1073741824 and 1 << 31 will be -2147483648, and so the while loop will never end if nSize is larger than 1073741824.

    With 1U << i, 1U << 31 will evaluate to 2147483648, and so you can safely use it for nSize up to 2147483647. If nSize is an unsigned int, it is also possible that the loop never ends, as in that case nSize can be larger than 1U << 31.

    Edit: So I disagree with the answers telling you nSize should be unsigned, but if it is signed then it should not be negative...

提交回复
热议问题