当编译器发现有符号/无符号不匹配时,它会采取什么措施?有符号数是否转换为无符号数,反之亦然?为什么?
最佳答案
如果操作数是整数且有一个无符号值,则转换为无符号。例如:
-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/