Pu Zhang
Pu Zhang

Reputation: 131

Declare an array in Fortran with the name of a parameter in another module

I'm pretty new in the Fortran world. I get a piece of code, where I find difficulty in understanding it.

Let's say in module A, var is declared as a parameter of integer type:

integer, parameter :: var = 81

Then in another module B, an array with the name var is declared:

integer :: var(2)

When these modules are used in a third module C:

use A
use B

Won't there be conflict in the names? Or the two members of the array var will take the value 81?

Upvotes: 3

Views: 1476

Answers (1)

casey
casey

Reputation: 6915

There will be a compile time error when you attempt to access the variable var in your described case. The specific error will look like:

Error: Name 'var' at (1) is an ambiguous reference to 'var' from module 'a'

Are those variables meant to be globally scoped? You can declare one (or both) of them with private so they are scoped to the module and do not pollute the global scope. In this case though, module C would not be able to use the private variable. Another option is to limit what is imported in your use statement with:

use A, only: some_variable1, some_other_variable
use B, only: var

This would let var from B into the scope of C, and would hide var from A.

If you have to have both variables in module C, you can rename one when you use the module. E.g.:

use A, varA => var
use B, varB => var

which lets you access the variables var in each module by the names varA and varB.

See this example:

module A
  integer, parameter :: var = 81
 contains
end module

module B
  integer :: var(2)
 contains
end module

module C
  use A, varA => var
  use B, varB => var
 contains
end module

program test
  use C    
  print *, varA
end program

which will print 81.

Upvotes: 8

Related Questions