Overflow and checked contexts

I’ve ended the previous post on numeric conversions talking about overflow and how it might surprise you from time to time. For instance, here’s an example that might get you off guard:

uint a = uint.MaxValue;
int b = (int)a;
Console.WriteLine("{0} – {1}", a,b);//-1

Running the previous snippet ends up printing the following:

4294967295 – -1

Now, even though this might be ok in several scenarios, there might some times when you want to get an exception if the value is “too big” for the variable. In these cases, you can resort to the checked keyword, which can be applied to a statement or expression, making it run in a checked context:

uint a = uint.MaxValue;
int b = checked((int)a); // throws OverflowException

In the previous snippet, the cast from the uint value into a int is perfomed in a checked context. Since the uint number is way “too big” to be stored in an int, we’ll end up getting a OverflowException. Besides casts, you can also use the checked keyword when performing arithmetic operations. Notice also that the checked keyword can be used to run an entire block of code in the checked context:

checked {
    uint a = uint.MaxValue;
    int b = (int) a; // throws OverflowException
}

In fact, and if that is your desire, you can also configure the C# compiler so that everything is run into a checked context by default. You can do this by passing the /checked flag from the command line or by going to the VS build tab on the project’s options windows and setting the  “Check for arithmetic overflow/underflow checkbox” on the dialog that is shown when you hit the advanced button.

In practice, you probably shouldn’t use checked contexts in all your arithmetic operations because checking contexts can make them really slow. If this is negligible or not, it will depend on the operations performed by your program. However, you should keep in mind that it might have some negative impacts in the performance of your app. Bottom line, if you decide to go crazy and run everything in the checked context, don’t forget to measure the impacts in the performance of the app.

And that’s it for now. Stay tuned for more.

Advertisements

~ by Luis Abreu on November 13, 2012.

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 )

Google+ photo

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

Connecting to %s

 
%d bloggers like this: