unsigned becomes signed in if-statement comparisons?

后端 未结 4 950
不思量自难忘°
不思量自难忘° 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条回答
  •  情深已故
    2020-12-18 00:36

    In the other answers we have seen that

    u16_varLow - u16_varHigh
    

    for you (with 16 bit short and 32 bit int) is equivalent to

    (int)u16_varLow - (int)u16_varHigh
    

    and thus its result is the int value -65525. Thus the assignment

    s16_Res1 = u16_varLow - u16_varHigh; 
    

    is equivalent to

    s16_Res1 = -65525;
    

    which in your case of 16 bit short yields "undefined behavior". You are just unlucky that your compiler decides to assign 11, instead. (Unlucky because I think that it is better to fail early.)

    In contrast to that

    u16_Res1 = -65525; 
    

    is a valid assignment since u16_Res1 is of an unsigned type and arithmetic of unsigned types is modulo the appropriate power of two.

提交回复
热议问题