添加两个无符号char变量,结果为int [英] Adding two unsigned char variables and result is int

查看:60
本文介绍了添加两个无符号char变量,结果为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有代码:

#include <iostream>
int main(){
  unsigned char a = 4, b = 255;
  int g = (unsigned char)a + (unsigned char)b;
  std::cout << g << std::endl;
  return 0;
}

结果:

259

为什么结果是259,而不是3?如果添加了两个无符号的char变量,则应该有溢出,结果应为3,然后应将其从无符号的char 3转换为int 3.

Why the result is 259, not 3? If there are added two unsigned char variables, there should be overflow, result should be 3 and then it should convert from unsigned char 3 to int 3.

推荐答案

添加操作将首先推广在进行加法之前,将操作数添加到 int .这就是C的工作方式.如果要截断,则需要将其分配回较窄的类型,例如 unsigned char .

The addition operation will first promote its operands to int, before doing the addition. This is how C works. If you want to truncate, you need to assign it back into a narrower type, such as unsigned char.

这篇关于添加两个无符号char变量,结果为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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