C中1U和1之间有什么区别吗? [英] Is there any difference between 1U and 1 in C?

查看:1089
本文介绍了C中1U和1之间有什么区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    while ((1U << i) < nSize) {
        i++;
    }

任何特殊原因使用 1U 而不是 1

Any particular reason to use 1U instead of 1?

推荐答案

在大多数编制者身上,两者都是将给出具有相同表示的结果。但是,根据C规范,对带符号参数的位移操作的结果给出了实现定义的结果,因此在 theory 1U<<我 1<< I 。在实践中,你遇到的所有C编译器都会将签名左移与无符号左移相同。

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.

另一个原因是如果 nSize 是无符号的,然后将其与签名的 1<<我将生成编译器警告。将 1 更改为 1U 可以删除警告消息,您不必担心会发生什么 i 是31或63。

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.

编译器警告很可能是 1U的原因出现在代码中。我建议在打开大多数警告的情况下编译C,并通过更改代码消除警告消息。

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.

这篇关于C中1U和1之间有什么区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆