Search code examples
return-valuefortran90subroutine

How to return a value from subroutine


I don't want to use global value it is dangerous for a big program. Code is like this

subroutine has_key(id)
  if (true) then 
     return 1
  else
     return 0
  end if
end subroutine

subroutine main
   if(has_key(id))
      write(*,*) 'it works!'
end subroutine

how can I do something like this using subroutine. I was thinking of return a flag but I may use a global value. Anyone has idea?


Solution

  • Like this

    subroutine test(input, flag)
       integer, intent(in) :: input
       logical, intent(out) :: flag
       flag = input>=0
    end subroutine
    

    and

    call test(3,myflag)
    

    will set myflag to .true.

    Note

    • that subroutines return values through their argument lists;
    • the use of the intent clause to tell the compiler what the subroutine can do with its arguments;
    • my example is very simple and you will probably want to adapt it to your needs.