unsigned long 0 < -1?

后端 未结 4 2225
南笙
南笙 2021-02-15 10:59

I don\'t get this one!

#include 

int main()
{
    unsigned short t1 = 0, t2 = 0;

    if( t1 < t2-1 )
        printf(\" t1 < t2-1\\n\");

          


        
4条回答
  •  花落未央
    2021-02-15 11:14

    C coercions, as you're discovering, are not always obvious, whenever you operate between different types. t2 is u16, 1 is int (presumably 32-bits), so t2-1 is exactly such an "operation between different types" and results in an overall coercion to int (as it's "longer" than u16...). Later, as s2 and 1 are both 32-bits (though of different signedness), the overall coercion is to unsigned long. So, the sizes of the types involved do help determine the signedness of the overall coercion.

    I suggest avoiding mixed-signedness (and ideally also mixed-size!) operations (via casting or special literal notation for literals such as 1 that otherwise will have int type and make your life potentially complicated and your code potentially unportable;-).

提交回复
热议问题