关于无符号数跟有符号数混合运算
关于无符号数和有符号数混合运算
大家好,我在dev c++上做了实验:
表达式a + b > 0返回的是false
表达式a + b > (unsigned)0返回的是true
表达式a + b > (short)0返回的是false
表达式a + b > (unsigned short)0返回的是false
表达式a + b > (char)0返回的是false
表达式a + b > (unsigned char)0返回的是false
一般如果表达式中包含无符号数,所有的常量和变量都会强制转换成无符号数,无论如何都应该返回true才对啊?
如果改成
就没问题了。
------解决方案--------------------
对于字符型类型,无论是有符号还是无符号,都是会先把字符型转换成int型来计算的,
所以 a + b > 0 是两个个int型在做运算, 结果也是int型, 大于号两边也是两个int型在比较
------解决方案--------------------
char 是向 int 提升
If an int can represent all values of the original type, the value is converted to an int;
otherwise, it is converted to an unsigned int. These are called the integer
promotions.48) All other types are unchanged by the integer promotions.
大家好,我在dev c++上做了实验:
unsigned char a = 1;
char b = -2;
表达式a + b > 0返回的是false
表达式a + b > (unsigned)0返回的是true
表达式a + b > (short)0返回的是false
表达式a + b > (unsigned short)0返回的是false
表达式a + b > (char)0返回的是false
表达式a + b > (unsigned char)0返回的是false
一般如果表达式中包含无符号数,所有的常量和变量都会强制转换成无符号数,无论如何都应该返回true才对啊?
如果改成
unsigned int a = 1;
int b = -2;
就没问题了。
------解决方案--------------------
对于字符型类型,无论是有符号还是无符号,都是会先把字符型转换成int型来计算的,
所以 a + b > 0 是两个个int型在做运算, 结果也是int型, 大于号两边也是两个int型在比较
------解决方案--------------------
char 是向 int 提升
If an int can represent all values of the original type, the value is converted to an int;
otherwise, it is converted to an unsigned int. These are called the integer
promotions.48) All other types are unchanged by the integer promotions.