How to use inteface blocks to pass a function to a subroutine?

前端 未结 3 657
旧巷少年郎
旧巷少年郎 2021-01-24 06:24

I understand the interface command can be used to pass a a function into a subroutine. So for example in the main program I\'d define some function and then pass it to some subr

3条回答
  •  Happy的楠姐
    2021-01-24 07:13

    A simple way to do this is to go old school and just leave the function external:

     program main
     real f,z
     external f
     call subr(f,z)
     write(*,*)z
     end
    
     real function f(x)
     real x
     f=x**2
     end
    

    ! below possibly in a precompiled library:

     subroutine subr(f,y)
     real f,y
     y=f(2.)
     end
    

    out: 4

    Of course with this approach you can not use advanced language features that require an explicit interface. **

    On the other hand if you are interfacing with standard libraries that need function arguments this is I think the only way.

    ** per MSB's comment you can handle that issue with an interface block in the subroutine, for example if we want to pass a function that returns an array:

     function f(x)
     real x,f(2)
     f(1)=x
     f(2)=x**2
     end
    

    as in the first example f is an external function, and the sub can be in a precompiled library:

     subroutine subr(g,y)
     interface
     function g(x)
     real x,g(2)
     end function
     end interface
     real y,z(2)
     z=g(2.)
     y=z(1)+z(2)
     end
    

    out: 6

    As noted, this is only strictly necessary if relying on language features that need the interface.

提交回复
热议问题