在Fortran中,PARAMETER
属性是在运行时还是编译时设置的?
我想知道我是否可以在运行时传递数组的大小并将其设置为PARAMETER
。
可以这样做吗?如果是这样,怎么样?如果没有,为什么?
答案 0 :(得分:2)
parameter
的值在编译时设置。
声明,例如
integer, parameter :: number_of_widgets = numwidge
要求在编译时知道numwidge
,在声明的 rhs 遇到它之前确实已知。
答案 1 :(得分:2)
如果要将数组的大小定义为运行时,则需要动态分配。所有参数(常量)必须定义为编译时间。
答案 2 :(得分:2)
是的,重复回答,命名常量(具有parameter
属性的对象)必须具有其初始值"在编译时已知#34;。但是,当你谈到数组的大小时,我会注意到其他的东西。
当声明数组的形状时,很多时候不需要通过常量表达式给出边界(其中一个简单的命名常量是一个例子)。所以,在主程序或模块中
implicit none
...
integer, dimension(n) :: array ! Not allowed unless n is a named constant.
end program
n
必须是常量。但是,在许多其他情况下,n
只需要一个规范表达式。
implicit none
integer n
read(*,*) n
block
! n is valid specification expression in the block construct
integer, dimension(n) :: array1
call hello(n)
end block
contains
subroutine hello(n)
integer, intent(in) :: n ! Again, n is a specification expression.
integer, dimension(2*n) :: array2
end subroutine
end program
也就是说,array1
和array2
是明确的形状自动对象。出于许多目的,人们并不真正需要命名常量。
除了数组大小之外,当然不允许使用以下内容。
implicit none
integer n, m
read(*,*) n, m
block
! n and m are specifications expression in the block construct
integer(kind=m), dimension(n) :: array ! But the kind needs a constant expression.
...
end block