3

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?

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Or (one) var can be renamed on the use statement.
strange that Fortran does not allow one use the module name as scope name, so one could have written A::var or A->var or A.var whatever the right syntax would be. having to rename things all the time does not seem like a good way to go about these things. This problem have been solved long time ago by Ada for example with its package system.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.