How arithmetic overflow check works in C #

It seems that arithmetic overflow checking is disabled by default in C # due to performance reasons (see https://stackoverflow.com/a/167328/) and so on.

But if I turn it on, either using the / checked flag or checked , how does the runtime actually perform a check? (I'm trying to better understand what "performance" is).

+4
source share
2 answers

Arithmetic operations, down to the hardware level, provide support for indicating whether the operation that was performed was overflowing. In many cases, this information will simply be ignored (and it is often ignored at a very low level), however, you can check this result after each individual operation and, if an overflow occurs, throw a new exception. Of course, all this verification, as well as the dissemination of this information through various levels of abstraction, is worthwhile.

+7
source

Overflow check in C # works using (or not use) overflow check in CIL.

For example, consider C # code:

public static int AddInts(int x, int y)
{
    return x + y;
}

Without overflow checking, it will compile something like this:

.method public hidebysig static int32 AddInts(int32 x, int32 y) cil managed 
{
    .maxstack 2
    IL_0000: ldarg.0
    IL_0001: ldarg.1
    IL_0002: add
    IL_0003: ret
}

With an overflow check, it will compile something like this:

.method public hidebysig static int32 AddInts(int32 x, int32 y) cil managed 
{
    .maxstack 2
    IL_0000: ldarg.0
    IL_0001: ldarg.1
    IL_0002: add.ovf
    IL_0003: ret
}

, CIL add, , checked unchecked #. , , , , #, , .

CIL, , , , . ( , .NET ), , jo x86.

, " ".

, unchecked , checked, , , . , , , - , . * , , , , .

unchecked.

, , .

32- () unchecked(x + y) " x y 32- ", checked(x + y) " x y 32- , ".

, unchecked(int.MaxValue + int.MaxValue) -2, , checked(int.MaxValue + int.MaxValue) , , .

, , -2.

, " , ?"

  • , , , : unchecked.
  • , , - , , : checked.
  • , , - : long BigInteger, int, , (, int, , ).
  • , , , , " " ": checked, unchecked , .

, , . , ( ?), , checked, , unchecked.

, ; "-", - .

- , " ", int , "" , .

, ", " - ; OverflowException, , , , , , , , . , , , , , .

:

  • , (-, unchecked) unchecked, .
  • , OverflowException, - () checked.
  • unchecked , checked , , . ( , , ).

* , , , , , . , , , .

+4

All Articles