3

I have the following module with an allocatable variable which is defined in the module, allocated in a subroutine, and then also used in a second subroutine called by the first subroutine. In this situation do I have to pass the variable to the second subroutine and declare INTENT(inout)? Or since it's a global variable it doesn't need to be passed as an argument?

MODULE test

  IMPLICIT NONE
  SAVE

  REAL,ALLOCATABLE,DIMENSION(:,:,:) :: total

CONTAINS

  !--- 1st subroutine
  SUBROUTINE my_subr1(n,m,z)
    IMPLICIT NONE
    INTEGER,INTENT(in) :: n,m,z
    ALLOCATE(total (n,m,z))
    total=.9
    CALL my_subr2(n)

  END SUBROUTINE my_subr1

  !-- 2nd subroutine
  SUBROUTINE my_subr2(n)
    IMPLICIT NONE
    INTEGER,INTENT(in) :: n

    total(n,:,:)=total(n-1,:,:)
  END SUBROUTINE my_subr2
END MODULE test
2
  • Use tag fortran for all Fortran questions. Commented Feb 25, 2019 at 8:23
  • 1
    All subroutine within the module have access to total. Module variables are "save" by default, also. Your code hass issues though (no declaration of dummy arguments in my_subr1 and no end module .... Commented Feb 25, 2019 at 9:36

1 Answer 1

5

do I have to pass the variable to the second subroutine and declare INTENT(inout)?

No, you don't. Any variable decalred in the body of the module has the save attribute by default. You must, though, ensure that the second subroutine is only called after the first was executed, or else the program will fail because total would not be initialized yet.

All functions and subroutines declared in the module will have access to total by host association.


By the way, there are some issues you should address in your code, as mentioned by @PierredeBuyl in the comments:

  • Variables declared in the module body are saved by default; you should remove the SAVE statement.
  • Procedures declared in a module inherit the IMPLICIT directive from the module scope, there is no need to redeclare it in the subroutine if you won't change it.
  • You are missing the declaration of the arguments in my_subr1.
Sign up to request clarification or add additional context in comments.

2 Comments

The save attribute isn't terribly relevant here. Even under Fortran standards where there isn't that attribute by default, the call from my_subr1 to my_subr2 means the variable doesn't go out of scope between the two.
thanks for the explanation, I have read about SAVE and IMPLICIT

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.