For programmers, when calculating, regarding overflow, I think I'm always careful, I will briefly summarize the cases that are often forgotten.
This article is a gaiden content picked up from the following contents.
To keep things simple, we'll assume a 32-bit signed integer type. Regarding the contents of this time, if it is a signed integer type with fixed precision, Other sizes should also apply.
In Java, C #, C / C ++ Think of int, Int32, int32, etc. (In C / C ++, it is assumed that the int type is a 32-bit processing system.)
Multiplication of large numbers is easy to overflow It's not the main subject because I think you can imagine it right away.
The main subject is the following cases.
int a = Int32.MinValue;
int b = -1;
int answer = a * b;
int a = Integer.MIN_VALUE;
int b = -1;
int answer = a * b;
int a = INT_MIN;
int b = -1;
int answer = a * b;
ʻA contains
-2147483648, Multiplying by
-1 exceeds
2147483647, which can be represented by a 32-bit signed integer. In my environment, the result of each ʻanswer
variable is -2147483648
.
For C #, if you set it to checked
, an OverFlowException will occur.
If the value can be evaluated at build or compile time, At that point, an overflow may be detected.
In integer division, if overflow does not occur, In some cases, it may be misunderstood, but it may overflow properly (?!).
int a = Int32.MinValue;
int b = -1;
int answer = a / b;
int a = Integer.MIN_VALUE;
int b = -1;
int answer = a / b;
int a = INT_MIN;
int b = -1;
int answer = a / b;
Similar to multiplication, but
Dividing by -1
is the same as multiplying by -1
, so
It exceeds 2147483647
, which can be represented by a 32-bit signed integer.
In my environment, in Java, the result of the ʻanswer variable is
-2147483648. In C ++, an integer overflow exception occurred. ** For C #, I get an OverFlowException regardless of whether it is
checked` or not. ** **
-1
does not always invert the sign (may overflow).