gpt4 book ai didi

c - C 中的无符号和有符号值

转载 作者:行者123 更新时间:2023-12-04 10:34:01 25 4
gpt4 key购买 nike

问题是:

在“计算机系统:程序员的视角”一书中第 2.2.5 节

它表示如果一个无符号值与一个有符号值进行比较,所有值都将以 unisnged 格式进行比较。像这样

if(-1 < 0u)
{
// will not print this line because -1 will be translated to 255.
printf("all changed to unsigned format");
}

我在 VC6 SP6 中试过这段代码,没有输出字符串。一切看起来都很好,因为我们都知道 -1 被翻译成 255。

但是当我读到“Expert C Programming Deep C Secrets”这本书的第 1.10 节时

它说如果我的编译器使用 ANSI C 标准,这段代码将打印“-1 < (unsigned char)1: ANSI”:

if(-1 < (unsigned char)1)
{
printf("-1 < (unsigned char)1: ANSI");
}
else
{
printf("-1 NOT Less than (unsigned char)1: K&R");
}

我得到的输出是:-1 < (unsigned char)1: ANSI。

我正在使用 VC6 SP6 编译器。

为什么会这样?

根据《计算机系统:程序员的视角》一书

-1 < (unsigned char)1 将使 -1 被翻译为无符号值。所以它会变成这样:

255 < 1

这不应该打印出行 -1 < (unsigned char)1: ANSI。

谁能告诉我为什么会这样?

最佳答案

if(-1 < (unsigned char)1)

在这种情况下,两个操作数都提升为 int .

if( -1 < 0u )

在这种情况下,两个操作数都转换为 unsigned int .

以下引述证明我是对的。

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:
— If either operand is of type long double, the other shall be converted to long double.
— Otherwise, if either operand is double, the other shall be converted to double.
— Otherwise, if either operand is float, the other shall be converted to float.
— Otherwise, the integral promotions (4.5) shall be performed on both operands.54)
— Then, if either operand is unsigned long the other shall be converted to unsigned long.
— Otherwise, if one operand is a long int and the other unsigned int, then if a long int can represent all the values of an unsigned int, the unsigned int shall be converted to a long int; otherwise both operands shall be converted to unsigned long int.
— Otherwise, if either operand is long, the other shall be converted to long.
— Otherwise, if either operand is unsigned, the other shall be converted to unsigned. [Note: otherwise, the only remaining case is that both operands are int ]

还有这个(积分促销):

An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; otherwise, the source rvalue can be converted to an rvalue of type unsigned int.

老实说,引用来自 C++03 标准,但它们也适用于 C。

关于c - C 中的无符号和有符号值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6799790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com