无符号整数,无符号的字符持有相同的价值尚未表现不同,为什么? [英] Unsigned integer and unsigned char holding same value yet behaving differently why?

查看:111
本文介绍了无符号整数,无符号的字符持有相同的价值尚未表现不同,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这样

unsigned char k=-1
if(k==-1)

为假

unsigned int k=-1
if(k==-1)

是真的

推荐答案

有关演示的目的,我们假设8位字符和32位 INT 秒。

For the purpose of demonstration let's assume 8-bit chars and 32-bit ints.

unsigned char k=-1;

K 被赋值为255。

if(k==-1)

== 的左侧运算符是一个 unsigned char型。右手边是一个 INT 。由于一个 unsigned char型的所有可能值可以装进一个 INT ,左手侧被转换为 INT (这是由于该整数促销执行,下面引用)。这导致在比较(255 == -1),这是错误的。

The left-hand side of the == operator is an unsigned char. The right-hand side is an int. Since all possible values of an unsigned char can fit inside an int, the left-hand side is converted to an int (this is performed due the the integer promotions, quoted below). This results in the comparison (255 == -1), which is false.

unsigned int k=-1

K 被赋值为4294967295

k is assigned the value 4294967295

if(k==-1)

这一次,左侧(一个unsigned int)不能一个int范围内适合。标准说,在这种情况下,这两个值被转换为一个unsigned int。因此,这将导致在比较(4294967295 == 4294967295),这是真的。

This time, the left-hand side (an unsigned int) cannot fit within an int. The standard says that in this case, both values are converted to an unsigned int. So this results in the comparison (4294967295 == 4294967295), which is true.

从标准的相关报价:

整数优惠:(C99,6.3.1.1p2)

Integer promotions: (C99, 6.3.1.1p2)

如果int可以重新present原始类型的所有值,该值被转换为int;否则,它被转换为unsigned int类型。

If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int.

常见算术转换:(6.3.1.8)

Usual arithmetic conversions: (6.3.1.8).

[对于整体操作数]整数促销活动是在两个操作数执行。然后下面的规则被施加到推动操作数:搜索
   - 如果两个操作数具有相同的类型,则不需要进一步的转换结果。
  ...结果
   - 否则,如果具有无符号整型操作数的等级大于或
  等于其它操作数的类型的秩,则与操作数
  有符号整数类型转换为无符号的操作数的类型
  整数类型。结果
  ...

[For integral operands, ] the integer promotions are performed on both operands. Then the following rules are applied to the promoted operands:
- If both operands have the same type, then no further conversion is needed.
...
- Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
...

这篇关于无符号整数,无符号的字符持有相同的价值尚未表现不同,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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