In addition to formal arguments, we can declare variables in a function or a subroutine. The scope rules state that these locally declared variables and parameters can only be used with that function or subroutine. Therefore, these variables are called local variables.
Arrays can also be declared in a function or subroutine. Since they are declared and used locally and are not formal arguments, local arrays cannot use INTENT(). So, the only one thing we have to know is the way of writing the extent in a local array declaration. It turns out that the extent of a local array is more flexible than that of a global array. Here are the rules:
PROGRAM Test .......... CONTAINS SUBROUTINE Sub(value) IMPLICIT NONE INTEGER, INTENT(IN) :: value INTEGER, PARAMETER :: SIZE = 5 REAL, DIMENSION(1:SIZE) :: Temp .......... END SUBROUTINE Sub END PROGRAM Test
In the above example, subroutine Sub() has two local arrays. Array a() has an extent 1:Len and array b() has an extent -Len:Len. Depending on the value of Len, the size of each array is different in each call.PROGRAM Main MODULE LocalArray IMPLICIT NONE .......... INTEGER :: Size = 10 CONTAINS INTEGER :: Value = 5 SUBROUTINE Sub(Len) .......... IMPLICIT NONE CALL Sub(Size) INTEGER, INTENT(IN) :: Len .......... INTEGER, DIMENSION(1:Len) :: a CALL Sub(Value) REAL, DIMENSION(-Len:Len) :: b .......... .......... END PROGRAM Main END SUBROUTINE Sub END MODULE LocalArray
Let us turn to the main program. The first call to Sub() has actual argument Size. Thus, Len in subroutine Sub() receives 10 and the extents of a() and b() are 1:10 and -10:10. The second call to Sub() has actual argument Value. In this case, Len receives 5 and the extents of a() and b() are 1:5 and -5:5.
If Sub() by passing a value of 5, then value receives 5 and the extent of array Temp() is 4:13. If Sub() is called with a value of 1, the extent of array Temp() becomes 0:5.PROGRAM MoreInteresting .......... CONTAINS SUBROUTINE Sub(value) IMPLICIT NONE INTEGER, INTENT(IN) :: value REAL, DIMENSION(value-1:2*value+3) :: Temp .......... END SUBROUTINE Sub END PROGRAM MoreInteresting
From the above discussion, we learn that local array provides an easy way for us to declare arrays locally rather than passing arrays around though formal argument which could cause a large number of formal arguments in a function or subroutine call. Since the extent of a local array could use formal arguments as well as constants, its size is flexible and determined when the function or subroutine is called.