从输入初始化的 Fortran PARAMETER 变量
Fortran PARAMETER variable initialized from input
在 Fortran 中,PARAMETER
属性是在 运行 时设置的还是在编译时设置的?
我想知道我是否可以在 运行 时传入数组的大小并将其设置为 PARAMETER
。
这能做到吗?如果是这样,如何?如果不是,为什么?
a parameter
的值是在编译时设置的。
声明如
integer, parameter :: number_of_widgets = numwidge
要求 numwidge
在编译时已知,确实在声明的 rhs 上遇到之前已知。
如果数组的大小要定义为运行时,则需要动态分配。所有参数(常量)必须在编译时定义。
是的,正如反复回答的那样,命名常量(具有 parameter
属性的对象)必须有其初始值 "known at compile time"。但是,当您谈论数组的大小时,我会注意其他事项。
当声明数组的形状时,很多时候边界不需要由常量表达式给出(其中一个简单的命名常量就是一个例子)。所以,在主程序或模块中
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
在 Fortran 中,PARAMETER
属性是在 运行 时设置的还是在编译时设置的?
我想知道我是否可以在 运行 时传入数组的大小并将其设置为 PARAMETER
。
这能做到吗?如果是这样,如何?如果不是,为什么?
a parameter
的值是在编译时设置的。
声明如
integer, parameter :: number_of_widgets = numwidge
要求 numwidge
在编译时已知,确实在声明的 rhs 上遇到之前已知。
如果数组的大小要定义为运行时,则需要动态分配。所有参数(常量)必须在编译时定义。
是的,正如反复回答的那样,命名常量(具有 parameter
属性的对象)必须有其初始值 "known at compile time"。但是,当您谈论数组的大小时,我会注意其他事项。
当声明数组的形状时,很多时候边界不需要由常量表达式给出(其中一个简单的命名常量就是一个例子)。所以,在主程序或模块中
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