You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Currently there is no standard, efficient way of detecting overflow/underflow in integer arithmetic.
Everyone has to devise their own functions and algorithms for checking if an overflow/underflow happened, which is tedious and likely to be inefficient.
I propose a new suite of functions in the math package.
Each one would return the result together with a boolean flag set to false when an overflow/underflow took place.
Closing as dup of #24853, and related to #30209 and #32063. Some of these functions are easily simulateable with math/bits operations.
Integer division can overflow, in the very special case of math.MinInt / -1.
And arguably, /0 also. Presumably DivOverflow would return false and not panic if dividing by 0.
Uh oh!
There was an error while loading. Please reload this page.
Currently there is no standard, efficient way of detecting overflow/underflow in integer arithmetic.
Everyone has to devise their own functions and algorithms for checking if an overflow/underflow happened, which is tedious and likely to be inefficient.
I propose a new suite of functions in the
math
package.Each one would return the result together with a boolean flag set to
false
when an overflow/underflow took place.func AddOverflow[T int | uint | int64 | uint64 | int32 | uint32 | int16 | uint16 | int8 | uint8](i T) (T, bool)
Add two integers and detect overflow.
func SubOverflow[T int | uint | int64 | uint64 | int32 | uint32 | int16 | uint16 | int8 | uint8](i T) (T, bool)
Subtract two integers and detect overflow.
func MulOverflow[T int | uint | int64 | uint64 | int32 | uint32 | int16 | uint16 | int8 | uint8](i T) (T, bool)
Multiply two integers and detect overflow.
func DivOverflow[T int | uint | int64 | uint64 | int32 | uint32 | int16 | uint16 | int8 | uint8](i T) (T, bool)
Divide two integers and detect overflow.
Example usage:
Another option would be to enhance the arithmetic operators to optionally allow two return values.
This however would constitute a language change.
The text was updated successfully, but these errors were encountered: