【发布时间】:2020-12-31 19:03:58
【问题描述】:
在 Fortran 中,PARAMETER 属性是在运行时还是编译时设置的?
我想知道是否可以在运行时传递数组的大小并将其设置为PARAMETER。
这可以吗?如果是这样,怎么做?如果不是,为什么?
【问题讨论】:
-
我不知道有更好的标题,但请注意,带有
parameter属性的东西不是变量。
标签: fortran
在 Fortran 中,PARAMETER 属性是在运行时还是编译时设置的?
我想知道是否可以在运行时传递数组的大小并将其设置为PARAMETER。
这可以吗?如果是这样,怎么做?如果不是,为什么?
【问题讨论】:
parameter 属性的东西不是变量。
标签: fortran
是的,正如反复回答的那样,命名常量(具有parameter 属性的对象)必须具有“在编译时已知”的初始值。但是,当您谈到数组的大小时,我会注意其他内容。
在声明数组的形状时,很多时候不需要用常量表达式给出边界(其中一个简单的命名常量就是一个例子)。所以,在主程序或模块中
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
【讨论】:
如果要将数组的大小定义为运行时,则需要动态分配。所有参数(常量)都必须定义为编译时间。
【讨论】:
parameter 的值是在编译时设置的。
声明如
integer, parameter :: number_of_widgets = numwidge
要求在编译时知道numwidge,在声明的rhs上遇到它之前确实知道。
【讨论】:
INTEGER, PARAMETER (n = variable) 其中variable 是从输入文件中读取的值吗?
variable 也是常量时。
variable。
config const 和config param。