Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shouldn't this cause an Overflow? It doesn't!

What's up with this, anyway? I do a simple multiplication:

Int64 x = 11111111111; Int64 y = 11111111111; Int64 z = x * y; 

And at the end of the multiplication, z shows a value of:

-5670418394979206991

This has clearly overflowed, but no exception is raised. I'd like one to be raised, but...

Note that this is on Windows Phone 7, but I don't think this has any bearing on the issue. Or does it?

like image 427
Cyberherbalist Avatar asked May 29 '10 09:05

Cyberherbalist


2 Answers

You can use a checked block as pointed out already by other answers:

checked {     long x = 11111111111;     long y = 11111111111;     long z = checked(x * y);     // ... } 

Which results in an exception:

OverflowException: Arithmetic operation resulted in an overflow.

If you are just doing a single operation where you need checking you can use a checked expression instead:

long x = 11111111111; long y = 11111111111; long z = checked(x * y); 

You can also set the /checked compiler option to have the default be checked.

To set this compiler option in the Visual Studio development environment:

  1. Open the project's Property Pages dialog box. For details, see Setting Visual C# Project Properties.
  2. Click the Configuration Properties folder.
  3. Click the Build property page.
  4. Modify the Check for Arithmetic Overflow/Underflow property.

If you change the default to checked you can use unchecked blocks or expressions to get the unchecked behaviour again.

like image 68
Mark Byers Avatar answered Oct 10 '22 02:10

Mark Byers


Check it:

checked {     Int64 x = 11111111111;     Int64 y = 11111111111;     Int64 z = x * y; } 
like image 29
Darin Dimitrov Avatar answered Oct 10 '22 02:10

Darin Dimitrov