C# Multiplying two variables of value int.MaxValue does not result in OverflowException -
i've got integer array contains 2 values, each maximum value of int32:
int[] factors = new int[] { 2147483647, 2147483647 };
i'm trying product of these 2 numbers create overflowexception:
try { int product = factors[0] * factors [1]; } catch(exception ex) { }
much surprise (and dismay), product returns value of 1. why this, , how go throwing exception when product of 2 integers exceeds int.maxvalue?
because default behavior of c# not check overflow int. however, can force overflow checking using checked
keyword.
try { checked { int product = factors[0] * factors [1]; } } catch(exception ex) { }
Comments
Post a Comment