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

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

Any particular reason to use 1U instead of 1?

相关标签:
4条回答
  • 2020-12-28 17:01

    1U is unsigned.

    The reason why they used an unsigned value in that is expression is (I guess) because nSize is unsigned too, and compilers (when invoked with certain parameters) give warnings when comparing a signed and an unsigned values.

    Another reason (less likely, in my opinion, but we cannot know without knowing wath value nSize is supposed to assume) is that unsigned values can be twice as big as signed ones, so nSize could be up to ~4*10^9 instead of ~2*10^9.

    0 讨论(0)
  • 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...

    0 讨论(0)
  • 2020-12-28 17:19

    1U is unsigned. It can carry values twice as big, but without negative values.

    Depending on the environment, when using U, i can be a maximum of either 31 or 15, without causing an overflow. Without using U, i can be a maximum of 30 or 14.

    31, 30 are for 32 bit int
    15, 14 are for 16 bit int

    0 讨论(0)
  • 2020-12-28 17:20

    On most compliers, both will give a result with the same representation. However, according to the C specification, the result of a bit shift operation on a signed argument gives implementation-defined results, so in theory 1U << i is more portable than 1 << i. In practice all C compilers you'll ever encounter treat signed left shifts the same as unsigned left shifts.

    The other reason is that if nSize is unsigned, then comparing it against a signed 1 << i will generate a compiler warning. Changing the 1 to 1U gets rid of the warning message, and you don't have to worry about what happens if i is 31 or 63.

    The compiler warning is most likely the reason why 1U appears in the code. I suggest compiling C with most warnings turned on, and eliminating the warning messages by changing your code.

    0 讨论(0)
提交回复
热议问题