对无符号整数的差异意想不到的效果 [英] Unexpected results on difference of unsigned ints

查看:122
本文介绍了对无符号整数的差异意想不到的效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶,这个功能对生产和DIF1 DIF2

I was surprised that this function produces different values for dif1 and dif2

void test()
{
    unsigned int x = 0, y = 1;
    long long dif1 = x - y;
    long long dif2 = (int)(x - y);
    printf("dif = %lld %lld",dif1,dif2);
}

是正确的行为?在DIF1计算它首先促进了32位无符号差为64位无符号值,然后增加的迹象。是标准的行为,而不是通过语言或编译器故障而规定的?在第二形式保证产生-1,或至多编译器执行?我想最安全的建设:
长长DIF3 =(久长)x - (久长)Y;

Is that correct behavior? In the dif1 computation it first promotes the 32-bit unsigned difference to a 64-bit unsigned value, then adds the sign. Is that standard behavior, not specified by the language, or a compiler bug? Is the second form guaranteed to produce -1, or up to the compiler implementation? I guess the safest construction is: long long dif3 = (long long)x - (long long)y;

推荐答案

第一种是绝对的定义,如果我们假设长长比更宽 unsigned int类型。如果不是,则分配给相同的问题的答案的第二部分

The first one is definitely defined, if we assume that long long is wider than unsigned int. If it isn't, then the assignment gives the same problem as the second part of the answer.

long long dif1 = x - y;

无符号整数将会换你可以存储在一个unsigned int类型的最大值。

Unsigned integers will wrap and you get a maximum value that can be stored in an unsigned int.

6.2.5 P9:在无符号操作数可以永远不会溢出的一种计算,
  因为不能再通过将得到的无符号整型psented $ P $结果为是
  减小模数比,可以是在一个最大值大的数目
  再由结果类型psented $ P $。

6.2.5 p9: A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.

结果
至于第二


As for the second

long long dif2 = (int)(x - y);

是实现定义的:

6.3.1.3 P3:否则,新的类型是有符号的,不能重新值$ P $在它psented;无论是
  结果是实现定义或实现定义的信号提高。

6.3.1.3 p3: Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

在这种情况下,为 unsigned int类型最大值不能再在 INT 蚂蚁psented $ P $上述规则生效。

In this case a maximum value for unsigned int cannot be represented in an int ant the above rule is in effect.

这篇关于对无符号整数的差异意想不到的效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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