error when defining function inside another function in fortran

user157588 :

For some use I need to define a function inside another function inside a fortran module. A sample code for easy comprehension is

module func
implicit none
contains

real function f(x,y)
real x,y,g

real function g(r)
real r
g=r
end function g

f=x*g(y)
end function f
end module func

use func
implicit none

write(*,*) f(1.0,1.0)
end

This is giving lots of errors in gfortran like unexpected data declaration, expected end function f, not g....etc.

What is the correct way of defining a function inside another function in fortran?

Ian Bush :

You use an internal subprogram, see below. Note internal subprograms themselves can not contain internal subprograms.

ian@eris:~/work/stack$ cat contained.f90
Module func

  Implicit None

Contains

  Real Function f(x,y)

    ! Interface explicit so don't need to declare g
    Real x,y

    f=x*g(y)

  Contains

    Real Function g(r)
      Real r
      g=r
    End Function g

  End Function f

End Module func

Program testit

  Use func

  Implicit None

  Write(*,*) f(1.0,1.0)

End Program testit
ian@eris:~/work/stack$ gfortran-8 -std=f2008 -Wall -Wextra -fcheck=all -O -g contained.f90 
ian@eris:~/work/stack$ ./a.out
   1.00000000    
ian@eris:~/work/stack$ 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=390721&siteId=1