Having parameter (constant) variable with NaN value in Fortran

To add to Vladimir F’s answer I’ll mention that gfortran 5.0 (but not earlier) supports the IEEE intrinsic modules.

Instead of

real x
x=0
x=0/x

one can use

use, intrinsic :: iso_fortran_env
use, intrinsic :: ieee_arithmetic
integer(int32) i
real(real32) x

x = ieee_value(x, ieee_quiet_nan)
i = transfer(x,i)

This gives you a little flexibility over which of the NaN values you get. You also needn’t worry about any signalling invalid flag. [But note that asking for ieee_signaling_nan may not really give you that.]

Note that ieee_value() can’t be used directly in initialization: a reference to it isn’t a constant expression. For such use, take this approach to get the bit pattern and apply the method of the other answer.

You’ll also need to ensure that there is the support for the features for each datatype.

Leave a Comment