Why integer zero does not equal long zero?

后端 未结 6 732
天命终不由人
天命终不由人 2020-12-11 00:28

A strange piece of code I\'ve just discovered in C# (should also be true for other CLI languages using .NET\'s structs).



        
6条回答
  •  渐次进展
    2020-12-11 01:00

    There is also the issue of narrowing or widening conversion. A long zero is always equal to an int zero, but not the other way around.

    When a long is compared to an int, only the least significant 32-bits are compared and the rest are ignored, thus the int.Equals(long) operation cannot guarantee equality even if the lower bits match.

    int a = 0;
    long b = 0;
    
    Trace.Assert(a.Equals((int)b));     // True   32bits compared to 32bits
    Trace.Assert(a.Equals((long)b));    // False  32bits compared to 64bits (widening)
    Trace.Assert(b.Equals((long)a));    // True   64bits compared to 64bits
    Trace.Assert(b.Equals((int)a));     // True   64bits compared to 32bits (narrowing)
    

    Also consider the case where the lower 32-bits are equal, but the upper ones are not.

    uint a = 0;
    ulong b = 0xFFFFFF000000;
    Trace.Assert((uint)a == (uint)b);  // true because of a narrowing conversion
    Trace.Assert((ulong)a == (ulong)b);  // false because of a widening conversion
    

提交回复
热议问题