gpt4 book ai didi

c - c中的数据类型提升

转载 作者:太空狗 更新时间:2023-10-29 17:18:35 28 4
gpt4 key购买 nike

在下面的代码中:

#include "stdio.h"
signed char a= 0x80;
unsigned char b= 0x01;


void main (void)
{
if(b*a>1)
printf("promoted\n");
else if (b*a<1)
printf("why doesnt promotion work?");

while(1);
}

我希望打印“promoted”。但它没有。为什么?如果我可以将数据类型设置为有符号和无符号 int,并将 a 作为负数,例如 0x80000000,将 b 作为正数 0x01,则“promoted”会按预期打印。

PLZ 帮助我了解问题所在!

最佳答案

您刚刚被 C 的困惑的类型提升规则所困扰。

在 C 中,小于 int 的整数类型的中间值会自动提升为 int

所以你有:

0x80 * 0x01 = -128 * 1

0x80 被签名扩展为 int 类型:

0xffffff80 * 0x00000001 = -128 * 1 = -128

所以结果是-128,因此小于1


当您使用 intunsigned int 类型时,两个操作数都会提升为 unsigned int0x80000000 * 0x01 = 0x80000000 作为一个大于 1 的无符号整数。


下面是正在发生的类型提升的并排比较:

(signed char) * (unsigned char) -> int
(signed int ) * (unsigned int ) -> unsigned int

(signed char)0x80 * (unsigned char)0x01 -> (int) 0xffffff80
(signed int )0x80000000 * (unsigned int )0x01 -> (unsigned int)0x80000000

(int) 0xffffff80 is negative -> prints "why doesnt promotion work?"
(unsigned int)0x80000000 is positive -> prints "promoted"

Here's a reference to the type-promotion rules of C.

关于c - c中的数据类型提升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9552703/

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