可以无符号整数递增导致未定义定义的行为? [英] Can unsigned integer incrementation lead to undefined defined behavior?

查看:193
本文介绍了可以无符号整数递增导致未定义定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里阅读64位 32位无符号乘法导致未定义的行为?问题在计算器上后,我开始思考无论是在小型无符号类型典型的算术运算可根据C99标准导致不确定的行为。

After reading the 32 bit unsigned multiply on 64 bit causing undefined behavior? question here on StackOverflow, I began to ponder whether typical arithmetic operations on small unsigned types could lead to undefined behavior according to the C99 standard.

例如,采取以下code:

For example, take the following code:

#include <limits.h>

...

unsigned char x = UCHAR_MAX;
unsigned char y = x + 1;

X 变量初始化为 unsigned char型数据类型的最大震级。下一行是问题:值 X + 1 UCHAR_MAX 较大,不能存储在 unsigned char型变量

The x variable is initialized to the maximum magnitude for the unsigned char data type. The next line is the issue: the value x + 1 is greater than UCHAR_MAX and cannot be stored in the unsigned char variable y.

我相信下面是实际发生的情况。

I believe the following is what actually occurs.


  • 变量 X 首次晋升为数据类型 INT (第 6.3.1.1/2 ),那么 X + 1 评估为数据类型 INT

  • The variable x is first promoted to data type int (section 6.3.1.1/2), then x + 1 is evaluated as data type int.

假设有一个实现,其中 INT_MAX UCHAR_MAX 是相同的 - X + 1 将导致一个有符号整数溢出。这是否意味着增加变量 X ,尽管是一个无符号整数类型,可能会导致不确定的行为,由于可能的符号整数溢出?

Suppose there is an implementation where INT_MAX and UCHAR_MAX are the same -- x + 1 would result in a signed integer overflow. Does this mean that incrementing the variable x, despite being an unsigned integer type, can lead to undefined behavior due to a possible signed integer overflow?

推荐答案

这是我的阅读标准,它使用一个15位的实施字符可以合法地保存 INT 作为一个15位的大小和使用第二个15位字来存储与填充的14位沿标志;在这种情况下,一个 unsigned char型将持有值0到32,767和 INT 将从-32,767保存值+ 32,767。加1 (unsigned char型)32767 的确是不确定的行为。类似的情况可以与任何较大的出现字符如果32,767与 UCHAR_MAX更换尺寸

By my reading of the standard, an implementation which used a 15-bit char could legally store int as a 15-bit magnitude and use a second 15-bit word to store the sign along with 14 bits of padding; in that case, an unsigned char would hold values 0 to 32,767 and an int would hold values from -32,767 to +32,767. Adding 1 to (unsigned char)32767 would indeed be undefined behavior. A similar situation could arise with any larger char size if 32,767 was replaced with UCHAR_MAX.

这样的情况是不可能的,但是,与无符号整数乘法相关的现实问题提到的其他职位相比。

Such a situation is unlikely, however, compared with the real-world problems associated with unsigned integer multiplication alluded to in the other post.

这篇关于可以无符号整数递增导致未定义定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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