2147483647 + 2147483647 = -2?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

how come when i add two Int32 vars in a try catch statement with the value
of 2147483647 it results in -2 instead of an exception?
 
Hi,

Overflow

From MSDN:
The Int32 value type represents signed integers with values ranging from
negative 2,147,483,648 through positive 2,147,483,647.

By default the int operations are not checked by overflow, for performance
reasons, you can set flag and the compiler will generate code to check that
it does not happen, it will throw an exception in that case.


cheers,
 
Jack said:
how come when i add two Int32 vars in a try catch statement with the value
of 2147483647 it results in -2 instead of an exception?

1) 2147483647 + 2147483647 stored in a signed 32-bit location overflows the
positive range, and results in a wrapped value which is -2 in this case.
Research integer overflow for more & complete details.

2) Integer overflow doesn't cause an exception.
 
Hi Jack,

You can force an overflow check and throw an exception.
The keyword to use is 'checked'/'unchecked'

int a = 2147483647;
int b = 2147483647;
int i = checked(a + b);
MessageBox.Show(i.ToString());

You can also cause all integer aritmetic to perform this check using the
/checked compiler option.
 
in addition, if you want overflowexception, you can either specify the
compiler flag csc /checked+, or use 'checked' keyword in your code, which
will generate the exception.
 
Julie said:
1) 2147483647 + 2147483647 stored in a signed 32-bit location overflows
the positive range, and results in a wrapped value which is -2 in this
case. Research integer overflow for more & complete details.

2) Integer overflow doesn't cause an exception.

I was not aware of the checked option as others have pointed out. I amend my
original response to:

2) Integer overflow doesn't cause an exception by default.
 
Back
Top