为什么在添加两个字符时没有整数溢出? [英] Why don't I get an integer overflow when adding two chars?

查看:104
本文介绍了为什么在添加两个字符时没有整数溢出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
两个字符相加会生成int

Possible Duplicate:
Addition of two chars produces int

给出以下C ++代码:

Given the following C++ code:

unsigned char a = 200;
unsigned char b = 100;

unsigned char c = (a + b) / 2;

根据逻辑上的预期输出为150,但是在表达式(a + b)中不应该存在整数溢出?

The output is 150 as logically expected, however shouldn't there be an integer overflow in the expression (a + b)?

很显然,这里必须有一个整数提升来处理溢出,否则我看不到发生了其他事情.我想知道是否有人可以启发我,所以我可以知道在整数提升和溢出方面我可以也不应该依靠它.

Obviously there must be an integer promotion to deal with the overflow here, or something else is happening that I cannot see. I was wondering if someone could enlighten me, so I can know what it is I can and shouldn't rely on in terms of integer promotion and overflow.

推荐答案

C ++和C都不使用较小"的整数类型(如charshort)执行算术计算.在开始任何进一步的计算之前,这些类型几乎总是被提升为int.因此,您的表情真的被评估为

Neither C++ not C perform arithmetical computations withing "smaller" integer types like, char and short. These types almost always get promoted to int before any further computations begin. So, your expression is really evaluated as

unsigned char c = ((int) a + (int) b) / 2;

P.S.在某些int范围不覆盖unsigned char范围的奇特平台上,类型unsigned int将用作促销的目标类型.

P.S. On some exotic platform where the range of int does not cover the range of unsigned char, the type unsigned int will be used as target type for promotion.

这篇关于为什么在添加两个字符时没有整数溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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