类型转换 - 无符号到有符号 int/char [英] Type conversion - unsigned to signed int/char

查看:45
本文介绍了类型转换 - 无符号到有符号 int/char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试执行以下程序:

#include <stdio.h>

int main() {
    signed char a = -5;
    unsigned char b = -5;
    int c = -5;
    unsigned int d = -5;

    if (a == b)
        printf("
 char is SAME!!!");
    else
        printf("
 char is DIFF!!!");

    if (c == d)
        printf("
 int is SAME!!!");
    else
        printf("
 int is DIFF!!!");

    return 0;
}

对于这个程序,我得到了输出:

For this program, I am getting the output:

字符是不同的!!!int 是一样的!!!

char is DIFF!!! int is SAME!!!

为什么我们会得到不同的输出?
应该输出如下吗?

Why are we getting different outputs for both?
Should the output be as below ?

字符是一样的!!!int 是一样的!!!

char is SAME!!! int is SAME!!!

一个 codepad 链接.

推荐答案

这是因为 C 中的各种隐式类型转换规则.C 程序员必须知道其中的两个:通常的算术转换整数提升(后者是前者的一部分).

This is because of the various implicit type conversion rules in C. There are two of them that a C programmer must know: the usual arithmetic conversions and the integer promotions (the latter are part of the former).

在 char 的情况下,您有 (signed char) == (unsigned char) 类型.它们都是小整数类型.其他这样的小整数类型是 boolshort.整数提升规则规定,每当一个小整数类型是一个操作的操作数时,它的类型将被提升为带符号的int.无论类型是有符号还是无符号,都会发生这种情况.

In the char case you have the types (signed char) == (unsigned char). These are both small integer types. Other such small integer types are bool and short. The integer promotion rules state that whenever a small integer type is an operand of an operation, its type will get promoted to int, which is signed. This will happen no matter if the type was signed or unsigned.

signed char 的情况下,符号将被保留,并将被提升为包含值 -5 的 int.对于 unsigned char,它包含一个值为 251 (0xFB) 的值.它将被提升为包含相同值的 int.你最终得到

In the case of the signed char, the sign will be preserved and it will be promoted to an int containing the value -5. In the case of the unsigned char, it contains a value which is 251 (0xFB ). It will be promoted to an int containing that same value. You end up with

if( (int)-5 == (int)251 )

<小时>

在整数情况下,您有 (signed int) == (unsigned int) 类型.它们不是小整数类型,因此整数促销不适用.相反,它们通过通常的算术转换来平衡,这表明如果两个操作数具有相同的等级"(大小)但符号不同,则有符号操作数将转换为与无符号操作数相同的类型.你结束了


In the integer case you have the types (signed int) == (unsigned int). They are not small integer types, so the integer promotions do not apply. Instead, they are balanced by the usual arithmetic conversions, which state that if two operands have the same "rank" (size) but different signedness, the signed operand is converted to the same type as the unsigned one. You end up with

if( (unsigned int)-5 == (unsigned int)-5)

这篇关于类型转换 - 无符号到有符号 int/char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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