unsigned becomes signed in if-statement comparisons?

后端 未结 4 949
不思量自难忘°
不思量自难忘° 2020-12-17 23:51

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 wo

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-18 00:42

    In the "usual arithmetic conversions", types smaller than int are promoted to either int or unsigned int before they are used in most expressions. The rule is that if int can represent all the values of the smaller type, then it is promoted to int; otherwise it is promoted to unsigned int. This is often considered something of a wart, because in many cases it causes unsigned char and unsigned short values to be promoted to int.

    This is exactly what you're seeing - u16_varLow and u16_varHigh and (unsigned short)5 are all promoted to int before the subtraction and comparison, which then happen using int. If you wish to be certain that an expression will use unsigned arithmetic, you must do it in unsigned int, not unsigned short:

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

提交回复
热议问题