Why should I explicitly surround with “unchecked”?

后端 未结 3 2002
余生分开走
余生分开走 2021-01-17 14:40

Is there anyone able to explain me this strange behavior?

    int i = 0x1234;
    byte b1 = (byte)i;
    byte b2 = (byte)0x1234;         //error: const value         


        
3条回答
  •  难免孤独
    2021-01-17 15:11

    This is not a strange behaviour, the valid range for a variable of the byte data type is 0-255 but when you convert HEX 0x1234 value into decimal system you got 4660. So unchecked used to control the overflow-checking integral-type arithmetic operations and conversions.

    You can find that unchecked often used in GetHashCode() implementation which does numeric operations to calculate the final hash code.

    To summarize you should use unchecked when the final result value of integer-type operations is not matter but overflow could happen.

提交回复
热议问题