无符号短并签订短期比较怪异行为 [英] unsigned short and signed short comparison wierd behavior

查看:128
本文介绍了无符号短并签订短期比较怪异行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我分配相同的价值符号和无符号并做失败的比较,但它与 INT 。除非我投一个或另一个,使他们同类型的比较是不工作。

When I assign the same value to signed and unsigned short and do a comparison it fails but it works with int. Unless I cast one or the other to make them same types the comparison is not working.

#include<stdio.h>

int main()
{
    signed short b = -10;
    unsigned short  c=-10;
    signed int a = -10;
    unsigned int d=-10;

    printf("%d , %d\n",b,(unsigned short)b);
    printf("%d , %d\n",(signed short)c,c);
    printf("%d , %u\n",a,(unsigned int)a);
    printf("%d , %u\n",(signed int )d,d);
    printf("b==c %d\n", b==c);
    printf("a==d %d\n", a==d);
    return 0;
}

输出:

./a.out
-10 , 65526
-10 , 65526
-10 , 4294967286
-10 , 4294967286
b==c 0
a==d 1

我在Sun Solaris的SPARC和HPUX安腾具有相同的输出跑到这一点。 (64位EXE文件)

I ran this in sun solaris sparc and hpux itanium with same output. (64 bit exes)

推荐答案

这是因为对C中的整数促销活动的规则。

This is because of the integer promotions rules of C.

下面是发生了什么:当您尝试比较不同类型的两个变量,编译器会检查每个类型可以被提升到一个 INT 。 A型可以晋升到 INT 时,其所有的可能值放入一个 INT 。如果一个类型可以提升到一个 INT ,它提升到 INT ;否则,编译器检查它是否能促进类型的无符号整型。如果本次促销是可能的,价值被提升到无符号整型在进行比较之前。

Here is what's going on: when you try comparing two variables of different types, the compiler checks if each type can be promoted to an int. A type can be promoted to int when all its possible values fit into an int. If a type can be promoted to an int, it is promoted to an int; otherwise, the compiler checks if it can promote the type to an unsigned int. If this promotion is possible, the value is promoted to unsigned int before proceeding with the comparison.

在你的第一个例子中,两个签订短期无符号短可以提升到一个 INT 。一旦做到这一点,你得到不同的值,因此比较返回

In your first example both signed short and unsigned short can be promoted to an int. Once this is done, your get different values, so the comparison returns false.

在你的第二个例子,但是,没有促销活动都做了,因为 INT 不能持有 unsigned int类型的所有值 ,反之亦然。在原始执行比较,其中比较相同的重presentations并返回

In your second example, however, no promotions are done, because int cannot hold all values of unsigned int and vice verse. The "raw" comparison is performed, which compares the same representations and returns true.

这篇关于无符号短并签订短期比较怪异行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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