stathisk
stathisk

Reputation: 234

Function doesn't return correct value

I am trying to write a Fortran 77 program where a subroutine makes a function call, with the function being provided as an argument (to the subroutine).

The problem I am facing is that function 'bar' doesn't return the correct result. Here is a minimal (not) working example:

% cat mwe.f
      real*8 function bar()
      print *,"bar:",bar
      bar = 101.0d00
      print *,"bar:",bar
      end

      subroutine foo(func)
      real*8 rv
      rv = func()
      print *,"rv:",rv
      end

      program tsig
      external bar
      call foo(bar)
      end
% gfortran mwe.f && ./a.out
 bar:   0.0000000000000000
 bar:   101.00000000000000
 rv:   0.0000000000000000
%

Upvotes: 0

Views: 633

Answers (2)

It was stated in the comments, but perhaps it should be said explicitly, because, you still appear to struggle. Keeping (pseudo) Fortran 77 you must do

  subroutine foo(func)
    real*8 rv
    real*8 func
    rv = func()
    print *,"rv:",rv
  end

The reason is that the type of func is assumed to be implicitly real inside foo. You must declare it explicitly if it returns some other type.

I strongly recommend to place implicit none at the start of each program and subroutine. It isn't part of Fortran 77 standard, but neither is real*8. Both are just common extensions. implicit none is standard in Fortran 90, real*8 is not standard Fortran at all.

Upvotes: 3

Oo.oO
Oo.oO

Reputation: 13385

code: simple.f

function bar()
  real*8 :: bar
  print *,"bar:",bar
  bar = 101.0d00
  print *,"bar:",bar
  return
end function bar

subroutine foo(func)
    interface
      function func()
        real*8 :: func
      end function func
    end interface
    real*8 rv
    rv = func()
    print *,"rv:",rv
end subroutine foo

program tsig
  external bar
  call foo(bar)
end

result:

./a.out
 bar:   2.1219959811805460E-314
 bar:   101.00000000000000
 rv:   101.00000000000000

Upvotes: 0

Related Questions