在以下代码中:
#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); }
我希望“促销”能够被印刷.但它没有.为什么?
如果我可以将数据类型设置为signed和unsigned int,并且具有负数,例如0x80000000,并将b作为正数0x01,则“promote”将按预期打印.@H_404_6@
PLZ帮助我了解问题所在!@H_404_6@
解决方法
你刚刚被C的凌乱的类型推广规则所困扰.
在C中,小于int的整数类型的中间体会自动提升为int.@H_404_6@
所以你有了:@H_404_6@
0x80 * 0x01 = -128 * 1
0x80被签名扩展为int类型:@H_404_6@
0xffffff80 * 0x00000001 = -128 * 1 = -128
所以结果是-128,因此小于1.@H_404_6@
当您使用int和unsigned int类型时,两个操作数都会被提升为unsigned int. 0x80000000 * 0x01 = 0x80000000作为无符号整数大于1.@H_404_6@
所以这里是正在进行的类型促销的并排比较:@H_404_6@
(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.@H_404_6@