C 中的无符号和有符号值
问题是:
在《计算机系统:程序员的视角》一书中的 2.2.5 节中,
它说如果无符号值与有符号值进行比较,则所有值都将以 unsnged 格式进行比较。像这样
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。
但是当我读到《专家 C 编程深度 C 秘密》一书的第 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 < (无符号字符)1:ANSI。
我正在使用 VC6 SP6 编译器。
为什么会发生这种情况?
根据《计算机系统:程序员的视角》一书
-1 < (unsigned char)1 将使 -1 被转换为无符号值。所以它会变成这样:
255 < 1
并且这不应该打印出 -1 < 行(无符号字符)1:ANSI。
谁能告诉我为什么会发生这种情况?
here is the question:
in the Book 'Computer Systems: A Programmer’s Perspective' section 2.2.5
it said that if an unsigned value is comparing with a signed value, all values will be compared in the unisnged format. like this
if(-1 < 0u)
{
// will not print this line because -1 will be translated to 255.
printf("all changed to unsigned format");
}
I tried this code in VC6 SP6, the string was NOT outputed. And everything looks good because we all know that -1 was translated to 255.
but when I read the book 'Expert C Programming Deep C Secrets' section 1.10
It said that if my complier uses the ANSI C Standard, this code will print "-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");
}
The output I got was: -1 < (unsigned char)1: ANSI.
I'm using the VC6 SP6 complier.
and why is this happening?
according to the book 'Computer Systems: A Programmer’s Perspective'
-1 < (unsigned char)1 will make -1 be translated as an unsigned value. so it will become sth like this:
255 < 1
and this should not print out the line -1 < (unsigned char)1: ANSI.
can anybody tell me why this is happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
if(-1 < (unsigned char)1)
在这种情况下,两个操作数都提升为
int
。if( -1 < 0u )
在这种情况下,两个操作数都转换为
unsigned int
。下面的引用证明我是对的。
并且这个(积分提升):
老实说,这些引号来自 C++03 标准,但它们也适用于 C。
if(-1 < (unsigned char)1)
In this case both operands are promoted to
int
.if( -1 < 0u )
In this case both operands are converted to
unsigned int
.The following quotes prove me right.
And this (integral promotions):
To be perfectly honest, the quotes are from the C++03 standard, but they hold for C as well.