3 ms·
> 1. Java does not trap overflows This one struck me some day because this is why Math.abs can return a negative value. When passing Integer.MIN_VALUE, the res
by nikeee 4y ago
> 1. Java does not trap overflows
This one struck me some day because this is why Math.abs can return a negative value. When passing Integer.MIN_VALUE, the result will be -2147483648.
There is now StrictMath.absExact that throws an exception in that case.
- divs1210 4y agoWow
- phoe-krk 4y agoThat's a known "feature" of most languages that perform modular arithmetic by default, since the negative of Integer.MIN_VALUE is Integer.MIN_VALUE in two's complement arithmetic. Languages that automatically promote to bignums by default (e.g. Lisp) do not suffer from this issue unless modular arithmetic is explicitly requested by the programmer.
- nikeee 4y agoI've a C# background and was pretty surprised about that. C# throws an exception in that case.
- phoe-krk 4y agoTIL! Thanks!
- lazulicurio 4y agoTo be slightly pedantic, C# gives you the option to throw an exception in that case (with either checked blocks or setting the CheckForOverflowUnderflow compiler flag to true), but the default behavior is to allow overflow.
- nikeee 4y agoI was under the impression that they compile with /checked per default. TIL! Regardless of that flag, Math.Abs will throw an OverflowException: https://referencesource.microsoft.com/#mscorlib/system/math.cs,3f2bea7ad215b3cc,references https://referencesource.microsoft.com/#mscorlib/system/math....
- lazulicurio 4y agoThe default actually depends on project language IIRC. C# has overflow checking disabled by default, VB.net has it enabled by default. Not sure about F#.