c++ - 当有符号/无符号不匹配时会发生什么转换?

标签 c++ casting warnings

当编译器发现有符号/无符号不匹配时,它会采取什么措施?有符号数是否转换为无符号数,反之亦然?为什么?

最佳答案

如果操作数是整数且有一个无符号值,则转换为无符号。例如:

-1 > (unsigned int)1 // as -1 will be converted to 2^nbits-1

转换int->unsigned int为:n>=0 -> n; n<0 -> n (mod 2^nbits),例如 -1 变为 2^nbits-1

转换unsigned int->int是:n <= INT_MAX -> n; n > INT_MAX -> 实现定义

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type).

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

关于c++ - 当有符号/无符号不匹配时会发生什么转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/838639/

相关文章:

c++ - openCV 中带垫子的动画

c++ - 从析构函数调用虚拟函数-有任何解决方法?

两个可能不相关的类之间的 Java 转换

java - 使用 'cast' 方法将 Integer 转换为 int 时自动装箱/拆箱

java - Java 中 int 的范围错误

android - 如何在整个项目中找到特定的警告

eclipse - 忽略 Eclipse 项目中的所有警告

c++ - 在二进制数据(密文)上使用 CryptoPP::Base64Encoder

java - "type X[][] should explicitly be cast to Object[][] for the invocation of the varargs"

c++ - 关于 std::string Action 的实现