How work on conversion in C # is checked and not checked

My question is about this code in programming in the C # console. I ask him with an example:

This code is not possible:

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 unchecked to make this code possible?

+4
source share
2 answers

Everything unchecked means that if the value overflows (crosses the border of MaxValue or MinValue ), an error does not occur, and this allows the wrapping to happen.

byte.MaxValue - 255 , 150 + 150 - 300 . Allowing overflow, it crosses the 255 boundary and starts counting again from byte.MinValue ( 0 in this case) to the final value 44 ( (150 + 150) - 256 = 44 )

+7
source

Overflow can be detected at compile time, since all expression conditions are constants.

If you replace it with

 int i = 150; byte sum = (byte)(i + i); 

It will compile fine.

Using unchecked , you are suppressing overflow-checking .

Even this does not compile -

 const int i = 150; byte sum = (byte)(i + i); 

due to the use of const keyowrd, which makes it available at compile time.

+3
source

Source: https://habr.com/ru/post/1495400/


All Articles