为什么我的 Fortran 模块不使我的索引变量可用?

Why is my Fortran module not making my index variable available?

这个问题是关于 Fortran 的。我需要将索引 i 从主程序(即 do i = 1,30 ...)传递给子例程。我已经创建了一个获取索引的模块,但不知何故它对其余子程序不可用。在下面的程序中,我想在子程序 vals4interp 中使用 index,我认为它应该可用,因为 index 是 public。然而实际上并没有。

program main_prog  
 ...  
 do i = 1, timesteps   
     ...   
     call getindex(i)  
 enddo  
 end main_prog  


module myindex  
 !   
 implicit none  
public  
 integer,public ::index  
contains  
! get index of loop  
subroutine getindex(index)  
integer, intent(inout)::index   

 print*,'in getindex', index  
end subroutine getindex  
!  
 subroutine vals4interp(ti,this,tvar)   
...  
 ! Here I need 'index', but it's 0 !  

call getindex(ti) !! this doesn't help... dunno why I thought it would ... 

end vals4interp

在例程getindex()中,变量index被用作伪参数。但是这个变量实际上是子程序中的一个局部变量,和模块变量index是不同的东西,虽然它们同名

subroutine getindex(index)  
    integer :: index    ! <--- this is a local variable different from the module variable "index"
    print*,'in getindex', index  
end subroutine getindex

更具体地说,如果相同的变量名(此处index)同时用于模块变量和伪参数,则局部变量优先,"hides"模块变量;也就是说,我们不能从例程 (*) 内部更改模块变量 index。要避免这种行为,只需将伪参数的名称从 index 更改为任何不同的名称,并使模块变量 index 从例程内部可见(可访问)。例如,

subroutine getindex( idx )  
    integer, intent(in) :: idx   ! <--- a local variable
    print*,'in getindex', idx
    index = idx                  ! <--- set module variable "index"
end subroutine getindex

通过此修改,子例程 vals4interp 应打印预期值。

(*) 相关页面请见Use variable from fortran subroutine argument list to set module variable of the same name