Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
28633 Discussions

Proper placement of "use" statement question

j0e
New Contributor I
307 Views
Hi All,

I recently had a bug in some code due to a variable getting redefined when I would have guessed it should have been flagged as a name conflict compilation error. Here is an example of the code:
[fortran]module globalV
   implicit none
   real temp
end module globalV

module system
   use globalV ! if this is commented out, then compile errors are reported; otherwise not.
   implicit none
   
   contains
   
   subroutine sub (a)
      use globalV
      real a
      real temp  ! why doesn't this cause a compilation error?
      a = temp
      return
   end subroutine sub

end module system

program test
   use globalV
   use system
   implicit none
   
   real a
   call sub (a)
   stop
end program test[/fortran]
If the "use globalV" statement is removed at the top of "module system", then the compiler properly flags the second declaration of variable temp as an error. However, when the use statement occurs as shown, no compiler or run errors occur.

Since I rely heavily on implicit none, I often don't focus on checking on variable name uniqueness. In the above case, "temp" in the globalV module was being used for temperature, while in the subroutine, it was just a "temp" variable.

I don't understand why the above code does not cause an error. Can someone elaborate why it shouldn't?

Thanks
-joe
0 Kudos
3 Replies
Steven_L_Intel1
Employee
307 Views
Well, this is interesting. The outer USE establishes TEMP as a local identifier in the scope of module SYSTEM. Inside SUB, TEMP is "host associated" and your declaration of TEMP as a variable overrides the host-associated name. This is the way the language is defined, but it can sometimes get you into trouble - see the "Up Periscope" section of Doctor Fortran in "Too Much of a Good Thing?"

When you have the USE only inside of SUB, then TEMP is use-associated and the language forbids you to declare another local identifier of the same name, so this is why you get an error when the outer USE is removed.

What puzzles me is that you get no error with both USE lines. It's as if the compiler is ignoring the second one because all the names are already defined. This may be a bug - I will have to study the standard to see.
0 Kudos
j0e
New Contributor I
307 Views
Thanks for the ref. Steve; it was useful. I think I will start using USE statements inside proceedures instead of relying on the host association, which basically caused my problem.

-joe
0 Kudos
Steven_L_Intel1
Employee
307 Views
Reported as issue DPD200171846.
0 Kudos
Reply