NaN set in a called FORTRAN function is returned as 4 instead of NaN

I have a FORTRAN function for which I am intentionally setting the floating point return value to NaN by assigning NaN=sqrt(-1.0) in cases where the calculation would be out of range. If I write the value to the sceen within the function itself it displays NaN like I want. When the function is called from an external program, the returning value is 4. I have tried using the ieee_is_nan function from ieee_arithmetic to check the returning value but it does not recognize the value as a NaN. What can I do to get a return value of NaN?

Do you have a reproducing example? I tried to replicate the issue, but it works as expected for me:

% cat nan.f90

function setnan (val)
     use ieee_arithmetic
     real :: setnan
     real :: val, negz
     negz = -1.
     val = sqrt(negz)
     print *, "Val is nan:  ", ieee_is_nan(val)
     setnan = val
end function setnan

program foo
    use ieee_arithmetic
    real :: setnan
    real :: rval, val
    val = 1
    rval = setnan(val)
    print *, "Rval is nan: ", ieee_is_nan(rval), rval
    print *, "Val2 is nan: ", ieee_is_nan(val), val
end program foo
% nvfortran nan.f90 ; a.out
 Val is nan:    T
 Rval is nan:   T             NaN
 Val2 is nan:   T             NaN

The function is part of a static library of functions that is later compiled with the external calling program. Displaying the value from the function itself works but the return value in the calling program ends up as 4. The library is a large code with multiple functions. I can try to make a simple example tomorrow that I can post.

image001.jpg

OK, I’m an idiot. After fighting with this all day I just now realized that the issue is that yesterday I changed the name of my function from VISL to my_pt but did not change the function name in the declaration which caused the function to be treated as an integer instead of a real. That is why the function itself recognized the NaN, but when it was returned to the calling program as an integer. The library won’t even compile with ieee_is_nan inside an integer function. It gives an error “Could not resolve generic procedure ieee_is_nan”. All is working now. Thanks!

image001.jpg

No worries. Glad you were able to determine the issue.

Granted I didn’t use “implicit none” in my toy example either, but the moral is to avoid Fortran implicit typing.