On Thu, 2013-12-26 at 07:00 +0000, Xiaogang Wang wrote:
> Hi,
> In the test code below, I first call a subroutine in a module to initialize
> a variable (pi) in the same module. I then use the module but the variable
> (pi) is not initialized. I would like to understand why this happens?
> Thanks for your help.
> Xiaogang
>
> !!!!!!!!!! the code starts
> module mymod
> public :: initialize_mymod
> public :: pi
> real*8 :: pi
> save
> contains
> subroutine initialize_mymod(pi)
> real*8, intent(in) :: pi
The dummy argument "pi" is a different variable from the module variable
"pi". It has the "intent(in)" attribute, so you can't assign a value to
it.
"real*8" was never part of any standard. Use "double precision" if
that's what you want, or "real(kind(0.0d0))" or "integer, parameter ::
WP = kind(0.0d0)" followed by "real(wp)" or "integer, parameter :: WP =
selected_real_kind(14)" etc. For your initializer you need something
like
subroutine initialize_mymod (value_to_initialize)
real(wp), intent(in) :: Value_To_Initialize
pi = value_to_initialize
end subroutine initialize_mymod
> write(*,'(a,f8.3)')'pi in initialize_mymod',pi
> end subroutine initialize_mymod
> end module mymod
>
> subroutine use_mymod()
> use mymod, only : pi
> write(*,'(a,f8.3)')'pi in use_mymod',pi
> end subroutine use_mymod
>
> program main
> use mymod, only : initialize_mymod
> real*8 :: pi
> pi = 3.14d0
> ! initialize pi in the module
> call initialize_mymod(pi)
>
> ! but pi is not initialized
> call use_mymod()
> end program main
> !!!!!!!!!! the code ends
>
>
> The result of the code is
> pi in initialize_mymod 3.140
> pi in use_mymod 0.000
|