为什么C ++将无符号的char值打印为负数? [英] Why does C++ prints unsigned char value as negative?

查看:174
本文介绍了为什么C ++将无符号的char值打印为负数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解C ++中的隐式转换规则,并且我了解到,当两种主要类型之间存在一种操作时,较低类型"将被提升为较高类型",所以可以这样说:

I'm trying to understand the implicit conversion rules in C++ and I understood that when there are one operation between two primary types the "lower type" is promoted to the "higher type", so let say for:

int a = 5;
float b = 0.5;

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

应该打印5.5,因为'a'被提升为浮点型.我还了解到,无符号类型比带符号的计数器部分是更高的类型",所以:

should print 5.5 because 'a' gets promoted to float type. I also understood that unsigned types are "higher types" than the signed counter parts so:

int c = 5;
unsigned int d = 10;

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

打印4294967291,因为'c'被提升为一个无符号的int,并且当小于零时,无符号的类型会回绕,我们得到了那个大数字.

prints 4294967291 because 'c' gets promoted to a unsigned int and since unsigned types wraps around when less than zero we get that big number.

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

However for the following case I don't understand why I am getting -105 instead of a positive number.

#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)不会影响最终的结果吗?

should result in a positive number so the final cast (to int) shouldn't affect the final result right?

推荐答案

引用 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.

以及通常的算术转换(针对这种情况)

....

  • 否则,必须对两个操作数执行积分提升(4.5)

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

and, finally, for integral promotions, chapter § 4.5

布尔值,布尔值,字符16或字符w32的整数类型以外的整数类型的pr值如果int可以表示所有整数,则rank(4.13)小于int的秩可以转换为 int 类型的prvalue源类型的值;否则,可以将源prvalue转换为 unsigned类型的prvalue诠释.

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 ,然后计算结果.

Hence, the unsigned char operands are promoted to int and then , the result is calculated.

这篇关于为什么C ++将无符号的char值打印为负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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