My question is about this code in a C# console programming I ask it with an example:
This code is impossible :
byte sum = (byte)(150 + 150); //impossible
but this code is possible :
byte sum = unchecked((byte)(150 + 150)); //possible
My question is: how does unchecked
work? I mean how does UNCHECKED
make this code possible?
All unchecked means is if the value overflows (crosses over the MaxValue
or MinValue
boundary) no error is thrown and it allows the wrap-around to happen.
The byte.MaxValue
is 255
, 150 + 150
is 300
. By allowing the overflow, it crosses over the 255
boundary and and starts counting again from byte.MinValue
(0
in this case) to reach a final value of 44
((150 + 150) - 256 = 44
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With