Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

You could also do it with a function. Say it returns true for even numbers

logical function has_key(id)
   integer, intent(in):: id
   has_key = mod(id,2) .eq. 0
end function has_key

program main
   do ii = 1, 4
      if(has_key(ii))
         print *, ii, ' has key'
      else
         print *, ii, ' no key'
      end if
   end do
end program
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top