Frank
Frank

Reputation: 574

Do COMMON blocks not name conflict with locally-defined variables in Fortran?

I am trying to overhaul some code to use modules instead of common blocks for globally-scoped variables.

During my refactor, I've been noticing lots of sections like this:

SUBROUTINE WEIRDSUB()
   INCLUDE 'parameters'
   COMPLEX BDY1, BDY2
   COMMON/FBDY/ BDY1(NY,NZ,NX), BDY2(NY,NZ,NX)
   ...
   ! NOTE: there is nothing here that assigns any values to BDY1
   ...
   CALL NORM(BDY1) ! runs no problem?
   ...

How is a having a locally-defined variable with the same name as a common block variable ok? Is the COMPLEX BDY1 declaration somehow imparting a type on the memory of the common block?

Upvotes: 0

Views: 168

Answers (2)

francescalus
francescalus

Reputation: 32366

complex bdy1

does not directly declare a local variable bdy1. It simply declares the type of some entity with name bdy1 to be complex.

This is true for other type declaration statements.

In this case the entity bdy1 is also declared to be in the common block, and an array with the given extents. There is no conflict.

Entities in common block may also be implicitly typed, or have a type declaration following the common statement (if it agrees with implicit typing rules).

Other examples of a type declaration statement not declaring local variables would be functions, dummy arguments, constants.

Upvotes: 1

Steve Lionel
Steve Lionel

Reputation: 7267

(See comments as the example changed a lot.) First, I'll note that the example you provide is not correct syntax. The fourth line should read:

COMMON /A/ A(NX,NY)

In most cases, a local name and a global name (the COMMON name is global) can't both be used in contexts where both are visible. There are exceptions, though. Quoting from the standard:

"Within its scope, a local identifier of an entity of class (1) or class (4) shall not be the same as a global identifier used in that scope unless the global identifier

  • is used only as the use-name of a rename in a USE statement,
  • is a common block name (19.3.2),
  • is an external procedure name that is also a generic name, or
  • is an external function name and the inclusive scope is its defining subprogram (19.3.3)"

The variable name is a class(1) entity (this is most local names) and the common block class(4). You can see that the common block name is an allowed exception. This works because you can't reference the common block name without the /A/ syntax, so it is not ambiguous.

Upvotes: 1

Related Questions