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

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

Any particular reason to use 1U instead of 1?

4条回答
  •  感情败类
    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.

提交回复
热议问题