views:

290

answers:

4

Handling integer overflow is a common task, but what's the best way to handle it in C#? Is there some syntactic sugar to make it simpler than with other languages? Or is this really the best way?

int x = foo();
int test = x * common;
if(test / common != x)
    Console.WriteLine("oh noes!");
else
    Console.WriteLine("safe!");
+1  A: 

Sometimes, the simplest way is the best way. I can't think a better way to write what you wrote, but you can short it to:

int x = foo();

if ((x * common) / common != x)
    Console.WriteLine("oh noes!");
else
    Console.WriteLine("safe!");

Note that I didn't remove the x variable because it'd be foolish to call the foo() three times.

TTT
Where is `test` initialized? I don't think your expression is quite right.
Michael Petito
Sorry fixed....
TTT
Now I wonder if the compiler would ever optimize that expression away entirely?
Michael Petito
USefull, unless of course you are planning on using the result (x*common), in that case your shortening would require the calculation to be done twice ...
Cobusve
+16  A: 

I haven't needed to use this often, but I believe you can use the checked keyword:

int x = foo();
int test = checked(x * common);

Will result in a runtime exception if overflows. From MSDN:

"In a checked context, if an expression produces a value that is outside the range of the destination type, the result depends on whether the expression is constant or non-constant. Constant expressions cause compile time errors, while non-constant expressions are evaluated at run time and raise exceptions."

I guess I should also point out that there is another C# keyword, unchecked, which of course does the opposite of checked and ignores overflows. You might wonder when you'd ever use unchecked since it appears to be the default behavior. Well, there is a C# compiler option that defines how expressions outside of checked and unchecked are handled: /checked. You can set it under the advanced build settings of your project (in VS2008 at least, not sure about VS2010).

So, if you had a lot of expressions that needed to be checked, the simplest thing to do would actually be to set the /checked build option. Then any expression that overflows, unless wrapped in unchecked, would result in a runtime exception.

Michael Petito
That's outstanding.
byte
+2  A: 

The best way is as Micheal Said - use Checked keyword. This can be done as :

int x = Max value for integer;
try   
{
    checked
    {
        int test = x * 2;
        Console.WriteLine("No Overflaw!");
    }
}
catch (OverflowException exc)
{
   Console.WriteLine("Overflow Exception  caught as: " + exc.ToString());
}
Chinjoo
You need to format your code (insert 4 spaces prior to it and the site will automatically pick up the formatting and syntax highlighting.
byte
thanks for the tip...
Chinjoo
+3  A: 

Try the following

int x = foo();
try {
  int test = checked (x * common);
  Console.WriteLine("safe!");
} catch (OverflowException) {
  Console.WriteLine("oh noes!");
}
JaredPar