1

How to avoid repeated declaration of a variable that has a constant value in subroutines?

For example:

program test
  implicit none

  integer :: n
  integer :: time

  print*, "enter n" ! this will be a constant value for the whole program
  call Calcul(time)
  print*, time  
end program

subroutine Calcul(Time)
  implicit none

  integer :: time 

  ! i don't want to declare the constant n again and again because some times the subroutines have a lot of variables.  
  time = n*2 
end subroutine

Sometimes there are a lot of constants that are defined by the user and I will make a lot of subroutines that use those constants, so I want to stock them and and use them without redefining them again and again.

2

1 Answer 1

5

For global variables use modules (old FORTRAN used common blocks, but they are obsolete):

module globals
  implicit none

  integer :: n

contains

  subroutine read_globals()    !you must call this subroutine at program start

    print*, "enter n" ! this will be a constant value for the whole program
    read *, n
  end subroutine
end module

!this subroutine should be better in a module too !!!
subroutine Calcul(Time)
  use globals !n comes from here
  implicit none

  integer :: time 
  time = n*2
end subroutine

program test
  use globals ! n comes from here if needed
  implicit none

  integer :: time

  call read_globals()

  call Calcul(time)

  print*, time
end program

There are many questions and answers explaining how to use Fortran modules properly on Stack Overflow.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks that works very well and easy, is there another way without using modules?
Yes, with common blocks. I don't recommend them at all. Modern Fortran is all about modules so you should learn to use them as much as possible.
In simple cases you can also make the subroutine to be internal to the program (put it between contains and end program.
The best solution I think is using module, thank you for your help!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.