无符号短和有符号短比较奇怪的行为 [英] unsigned short and signed short comparison wierd behavior

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

问题描述

当我将相同的值分配给有符号和无符号的 short 并进行比较时,它失败了,但它适用于 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
",b,(unsigned short)b);
    printf("%d , %d
",(signed short)c,c);
    printf("%d , %u
",a,(unsigned int)a);
    printf("%d , %u
",(signed int )d,d);
    printf("b==c %d
", b==c);
    printf("a==d %d
", a==d);
    return 0;
}

输出:

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

我在 sun solaris sparc 和 hpux itanium 中以相同的输出运行它.(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.当一个类型的所有可能值都适合一个 int 时,它可以被提升为 int.如果一个类型可以提升为int,则将其提升为int;否则,编译器会检查它是否可以将类型提升为 unsigned int.如果此提升是可能的,则在进行比较之前,该值将提升为 unsigned 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.

在您的第一个示例中,signed shortunsigned short 都可以提升为 int.完成此操作后,您将获得不同的值,因此比较返回 false.

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 的所有值,反之亦然.执行原始"比较,比较相同的表示并返回 true.

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

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

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