整数溢出和未定义行为 [英] Integer overflow and undefined behavior

查看:150
本文介绍了整数溢出和未定义行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关于检测整数溢出,因为可能的未定义行为若干问题的实际加法/减法了。所以,我的问题是,

There are many questions about detection of the integer overflow BEFORE the actual addition/substraction because of possible undefined behavior. So, my question is

为什么它会在第一时间产生这种未定义行为

Why it will produce this undefined behavior in the first place?

我能想到的2原因:

1),在这种情况下,产生异常的处理器。当然,它可以切换关闭,并极有可能写得很好CRT将这样做。

1) A processor that generates exception in this case. Sure, it can be toggled off, and most probably a well written CRT will do that.

2)使用数字的其他二进制重新presentations(1的补?基地10?)的处理器。在这种情况下,不确定的行为本身会表现为不同的结果(但不会崩溃!)。好了,我们可以住在一起。

2) A processor that uses other binary representations of numbers (1's complement? base 10?). In that case the undefined behavior will manifest itself as different result (but will not crash!). Well, we could live with that.

那么,为什么有人要避免造成的呢?我缺少的东西吗?

So, why should someone avoid causing it? Am I missing something?

推荐答案

虽然的的现代CPU使用2的补,并在predictable模环绕整数溢出的结果,这绝不是万能 - 要保持足够的语言一般,它可以在最广泛的架构,最好指定整数溢出是UB使用

Although most modern CPUs use 2's complement, and integer overflow results in predictable modulo wraparound, this is by no means universal - to keep the language sufficiently general that it can be used on the widest range of architectures it's better to specify that integer overflow is UB.

这篇关于整数溢出和未定义行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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