问题
An integer variable declared in the module is used as a global variable to define the size of related arrays in the program. The size of program varies, so the size of array is a variable but not a parameter. It is determined at the beginning of the program.
In the following snippet of code, n
is the global size variable. It is declared in the module and defined at the beginning of main function/program. Similar usage of n
in the main program and the subroutine contained in the main program to initialise an array respectively. However, the initialisation in the main program causes the error: module or main program array must have constant shape error, but the initialisation in subroutine works. What is the mechanism behind this different treatment of non-constant values used in different positions?
module mod
implicit none
integer :: n
end module mod
program main
use mod
implicit none
integer :: b(n)
n = 5
b(:) = 1
print*, b(:)
call sub
contains
subroutine sub
integer :: a(n)
a = 10
print*, a
end subroutine sub
end program main
回答1:
An array declared like a(n)
is an explicit shape array. When n
is not a constant (named or otherwise, strictly a constant expression) such an array is an automatic object.
Automatic objects are restricted in where they may appear. In particular, an explicit shape array is subject to the following constraint (C531 of F2008):
An explicit-shape-spec whose bounds are not constant expressions shall appear only in a subprogram, derived type definition, BLOCK construct, or interface body.
As n
from the module mod
is not a constant it cannot be used as bounds of an array in the main program. The subroutine sub
is a subprogram and so a(n)
is a valid use of a non-constant bound.
Instead of having an automatic object in the main program, one can instead consider deferred shape arrays, using either pointer
or allocatable
attributes.
来源:https://stackoverflow.com/questions/45711764/module-or-main-program-array-must-have-constant-shape-error-in-fortran