Unintuitive module variable scope

Hi everyone,

Debugging an unusual problem with my code, I found some interesting behavior in resolving variable scope when using variables declared in fortran modules. See the example below. Is this normal behavior?

module foo
  implicit none
  real :: duck = 5
end module foo

module bar
  use foo, only: duck
  implicit none
  subroutine foobar()
    use foo
    implicit none
! Here there is no ambiguity. Uncommenting the line below triggers a syntax error
!    real :: duck
    write (*,*) "duck=",duck
  end subroutine foobar

  subroutine foobar2()
    implicit none
! Here the compiler is happy taking variable "duck" from module foo
    write (*,*) "duck=",duck
  end subroutine foobar2
  subroutine foobar3()
    implicit none
    real :: duck=4.
! Here the compiler uses the local variable a, overrides "use foo"
    write (*,*) "duck=",duck
  end subroutine foobar3

end module bar

program test
  use bar
  call foobar()
  call foobar2()
  call foobar3()

end program test

[halpernf@summit1 ~]$ mpif90 -o foobar foobar.f90 
[halpernf@summit1 ~]$ ./foobar 
 duck=    5.000000    
 duck=    5.000000    
 duck=    4.000000

In the subroutine foobar, a declaration of a variable duck is incorrect. This is because the variable of module foo duck is use associated in the subroutine itself.

In foobar3, the variable duck of module bar has been host associated. With host association it is allowed to have a local variable of the same name as the entity in the host (making the host entity inaccessible). The fact that the variable duck of module bar is use associated with the variable duck of module foo does not affect that.

The “import, [none, all, only]” statements may be of interest when considering such concerns.