Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29246 Discussions

How to return a value from a fortran function

Seyhan_Emre_G_
Beginner
2,651 Views

I would like to return a value from a function to the main program. I would also like to be able to use that value at the main function. Here is an example that doesn't work.

 

    

      program trial

      real*8 a,b,c

      a=1.d0

      b=0.d0

     

      call fn(a,b,c)

     

      if (fn.eq.1) write(*,*)

  

      end program trial

 

      function fn(a,b,c)

      real*8 a,b,c

     

      if (a.gt.0) return 0

 

      return 1

      end function fn

0 Kudos
2 Replies
Mark_Lewy
Valued Contributor I
2,651 Views

Your function could be written as

[fortran]

function fn(a, b, c)

    integer :: fn ! I'm declaring the function return value as integer here because of the integer return values in the original code, implicit typing would make it real otherwise.

    real*8 a, b, c

    if (a .gt. 0) then

        fn = 0 ! This assignment sets the return value of the function...

        return

    end if

    fn = 1 ! ... and so does this

end function

[/fortran]

You will need to declare the function as integer fn in your program.

To call it, either

a) Declare an integer in your program to receive the return value, say retval and call the function with retval = fn(a,b,c); if (retval .eq. 1) write(*,*)

b) Call the function in the if statement: if (fn(a,b,c) .eq. 1) write(*,*)

0 Kudos
Seyhan_Emre_G_
Beginner
2,651 Views

Hello Mark,

 

Thank you.

0 Kudos
Reply