无符号成为if语句比较签名吗? [英] unsigned becomes signed in if-statement comparisons?

查看:108
本文介绍了无符号成为if语句比较签名吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索这个网站的答案,发现无符号/符号比较多的响应,但这个问题是,只有无符号的参数进行比较,但还是它的工作原理好笑。

I have searched this site for an answer and found many responses to unsigned/signed comparison but this problem is that only unsigned parameters are compared but still it works funny.

具有以下code的问题是,在第一个如果 -statment不会发生(你好),其中作为第二个(世界)执行。这个我已经跨preTED为被内部完成计算的如果 -statment产生负数而是保存到一个变量的结果做了完全一样的计算不没有(即使结果被保存到一个符号变量)。

The problem with the following code is that the first if-statment does not happen ("hello") where as the second ("world") does. This I have interpreted as the calculation that is done inside the if-statment generates a negative number but the exact same calculation done with the result saved to a variables does not (even though the result is being saved to a signed variable).

所使用的编译器是gcc 4.4。

The compiler used is gcc 4.4.

unsigned short u16_varHigh;  
unsigned short u16_varLow;  
unsigned short u16_Res1;  
signed short   s16_Res1;  

u16_varHigh = 0xFFFF;  
u16_varLow = 10;

u16_Res1 = u16_varLow - u16_varHigh; // response is 11 as expected  
s16_Res1 = u16_varLow - u16_varHigh; // response is 11 as expected

// Does not enter  
if( (u16_varLow - u16_varHigh) > (unsigned short)5 )  
{  
 printf( "hello" );  
}

// Does enter  
if( (unsigned short)(u16_varLow - u16_varHigh) > 5 )  
{  
 printf( "world" );  
}

任何人都可以解释这对我来说,也许拿出一个固定的解决方案,使第一如果语句来工作呢?

推荐答案

在除权pression:

In the expression:

if( (u16_varLow - u16_varHigh) > (unsigned short)5 )  

(u16_varLow - u16_varHigh)将被提升到一个 INT 和评价-65525。有关问题的解决方法是强制转换为无符号的类型,像你一样,在是否进入 - code

(u16_varLow - u16_varHigh) will be promoted to an int and evaluate to -65525. The fix for your problem is to cast to an unsigned type, like you do in the "Does enter"-code.

究其原因 s16_Res1 = u16_varLow - u16_varHigh; 11得到的是减法,-65525的结果,不适合在短期

The reason s16_Res1 = u16_varLow - u16_varHigh; yields 11 is that the result of the subtraction, -65525, doesn't fit in a short.

这篇关于无符号成为if语句比较签名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆