c中的数据类型提升
发布时间:2020-12-16 03:19:13 所属栏目:百科 来源:网络整理
导读:在以下代码中: #include "stdio.h"signed char a= 0x80;unsigned char b= 0x01;void main (void){ if(b*a1) printf("promotedn"); else if (b*a1) printf("why doesnt promotion work?"); while(1);} 我希望“促销”能够被印刷.但它没有.为什么? 如果我可
在以下代码中:
#include "stdio.h" signed char a= 0x80; unsigned char b= 0x01; void main (void) { if(b*a>1) printf("promotedn"); else if (b*a<1) printf("why doesnt promotion work?"); while(1); } 我希望“促销”能够被印刷.但它没有.为什么? PLZ帮助我了解问题所在! 解决方法
你刚刚被C的凌乱的类型推广规则所困扰.
在C中,小于int的整数类型的中间体会自动提升为int. 所以你有了: 0x80 * 0x01 = -128 * 1 0x80被签名扩展为int类型: 0xffffff80 * 0x00000001 = -128 * 1 = -128 所以结果是-128,因此小于1. 当您使用int和unsigned int类型时,两个操作数都会被提升为unsigned int. 0x80000000 * 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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |