Programming-Idioms

History of Idiom 86 > diff from v19 to v20

Edit summary for version 20 :
New Fortran implementation by user [tkoenig]

Version 19

2019-09-27, 23:34:40

Version 20

2019-09-29, 11:23:41

Idiom #86 Check if integer multiplication will overflow

Write boolean function multiplyWillOverflow which takes two integers x, y and return true if (x*y) overflows.

Idiom #86 Check if integer multiplication will overflow

Write boolean function multiplyWillOverflow which takes two integers x, y and return true if (x*y) overflows.

Code
  logical function multiply_will_overflow (x, y) result(res)
    integer, intent(in) :: x, y
    integer, parameter :: ik = selected_int_kind (int(digits(y)*log10(2.)*2))

    res = int(x,kind=ik) * int(y,kind=ik) > huge(x)
  end function multiply_will_overflow
Comments bubble
The only standard way to do this in Fortran, without invoking undefined behavior, is to perform the multiplication with integer type that can hold the result and check for the overflow.