#59 – Using Unchecked Keyword to Avoid Overflow Exceptions

If the default project setting is to check for arithmetic overflow/underflow, you can temporarily avoid checking using the unchecked keyword.  This reverts to the default behavior of wrapping the result value.

Assume that we’ve changed the project setting so that we do check for arithmetic overflow.  We can then avoid an exception by using the unchecked keyword on an expression:

 int n1 = int.MaxValue;   // 2147483647 (0x7FFFFFFF)
 int n2 = unchecked(n1 + 1);  // Wraps: -2147483648
 int n3 = n1 + 1;             // Throws OverflowException--default project setting

We can also use the unchecked keyword on an entire statement block:

 int n1 = int.MaxValue;   // 2147483647 (0x7FFFFFFF)
 unchecked
 {
     int n2 = n1 + 1;  // Wraps: -2147483648
     int n4 = n1 * 2;  // Wraps: -2
 }

You can also use unchecked to avoid overflow checking on constant expressions at compile-time.  This results in no compile-time error and no overflow exception at run-time.

 int n1 = int.MaxValue + 1;  // Compile-time error: overflow
 int n2 = unchecked(int.MaxValue + 1);
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #59 – Using Unchecked Keyword to Avoid Overflow Exceptions

  1. Joey says:

    Never knew about the unchecked keyword. Not sure if I’ll ever need it but it’s good to know, thanks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: