Reputation: 55
Let's say I have two subroutines
SUBROUTINE S2909
COMMON X,Y
X =2;
Y =3;
END
SUBROUTINE S2900
COMMON X,Y
//display X and Y
END
A COMMON block is used for sharing variables so does this mean if the value of X
, Y
that is updated in the subroutine S2909
will be same as in subroutine S2900
?
Upvotes: 2
Views: 165
Reputation: 32451
This sharing is indeed the point of common blocks. In particular, the common
statement allows so-called storage association between various entities throughout a program.
So, the entities X
and Y
in the subroutine S2909
are storage associated with the entities X
and Y
in the subroutine S2900
. Changes to the value in one entity X
are reflected by the other entity X
.
There are a few things worth noting about this, though.
In the common
statements of the question this is relying on what is known as blank common. This is what happens when there is no name specified for a common block, such as in the statement
common /named/ x, y
This is noteworthy because attempting to generalize the behaviour in this question to named common blocks may be troublesome.
The entities in the various places where the common blocks are referenced are associated not by name, but by order in the storage sequence. This means that care must be made with say
SUBROUTINE S2909
COMMON X,Y
END
SUBROUTINE S2900
COMMON Y,X
END
But my answer really has two points to make, and the above was just a preamble to make it more answer-like.
First, I'll mention a pathological case which I wouldn't expect to see in the wild.
The question is relying on implicit typing. Consider the following
subroutine S2909
common x, y
x = 2.
y = 3.
end subroutine S2909
implicit integer (a-z)
call S2909
call S2900
contains
subroutine S2900
common x, y
print*, x, y
end subroutine
end
This is an example of uncivil code writing, but it illustrates an important thing. Because the entities x
in the S2909
and x
in the subroutine S2900
are of different types defining one of them causes the other to become undefined. That is: updating the value of one doesn't update the value of the other. With explicit typing one could see the same thing, or if there was implicit typing with default rules and entities i
and j
, say, in one subroutine.
And the final thing I want to say is: there are much better ways of sharing data "globally" without common blocks.
Upvotes: 1
Reputation: 183
From my understanding, yes, the variables are shared throughout the program. Their values will depend on the order with which the subroutines are called.
The following program
program test
real x,y
common x,y
x = 1
y = 2
write(*,*) x,y
call changevals
write(*,*) x,y
end program test
subroutine changevals
real x,y
common x,y
x = 12
y = 13
end subroutine changevals
outputs
1.00000 2.00000
12.00000 13.00000
Upvotes: 1