Print to standard output from a function defined in an Fortran module

Your program does what is known as recursive IO – the initial call to plgndr is in the output item list of an IO statement (a print statement) [directing output to the console] – inside that function you then also attempt to execute another IO statement [that outputs to the console]. This is not permitted – see 9.11p2 and p3 of F2003 or 9.12p2 of F2008.

A solution is to separate the function invocation from the io statement in the main program, i.e.

REAL :: a_temporary
...
a_temporary = plgndr(1,2,0.1)
PRINT *, a_temporary

Other alternatives in F2008 (but not F2003 – hence the [ ] parts in the first paragraph) include directing the output from the function to a different logical unit (note that WRITE (*, ... and PRINT ... reference the same unit).

In F2008 you could also replace the WRITE statement with a STOP statement with a message (the message must be a constant – which wouldn’t let you report the problematic values).

The potential for inadvertently invoking recursive IO is part of the reason that some programming styles discourage conducting IO in functions.

Leave a Comment