+-
为什么C将unsigned char值打印为负值?
我试图理解C中的隐式转换规则,我理解当两个主要类型之间有一个操作时,“低级类型”被提升为“更高类型”,所以让我们说:

int a = 5;
float b = 0.5;

std::cout << a + b << "\n";

应该打印5.5因为’a’被提升为浮点类型.我也明白,无符号类型比签名的计数器部分“更高类型”所以:

int c = 5;
unsigned int d = 10;

std::cout << c - d << "\n";

打印4294967291,因为’c’被提升为unsigned int,并且由于unsigned类型在小于零时回绕,我们得到那么大的数字.

但是对于以下情况,我不明白为什么我得到-105而不是正数.

#include <iostream>

int main(void) {
    unsigned char a = 150;
    std::cout << static_cast<int>(a - static_cast<unsigned char>(255)) << "\n";
    return 0;
}

我想这段代码:

a - static_cast<unsigned char>(255)

应该得到一个正数,所以最终的演员阵容(对于int)不应该影响最终结果吧?

最佳答案
引自C 14,第5.7章

The additive operators + and - group left-to-right. The usual arithmetic conversions are performed for
operands of arithmetic or enumeration type.

对于通常的算术转换,(特定于此情况)

….

Otherwise, the integral promotions (4.5) shall be performed on both operands

最后,对于整体促销,第4.5节

A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion
rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all
the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned
int.

因此,unsigned char操作数被提升为int,然后计算结果.

点击查看更多相关文章

转载注明原文:为什么C将unsigned char值打印为负值? - 乐贴网