【问题标题】:Fortran PARAMETER variable initialized from input从输入初始化的 Fortran PARAMETER 变量
【发布时间】:2020-12-31 19:03:58
【问题描述】:

在 Fortran 中,PARAMETER 属性是在运行时还是编译时设置的? 我想知道是否可以在运行时传递数组的大小并将其设置为PARAMETER

这可以吗?如果是这样,怎么做?如果不是,为什么?

【问题讨论】:

  • 我不知道有更好的标题,但请注意,带有parameter 属性的东西不是变量。

标签: fortran


【解决方案1】:

是的,正如反复回答的那样,命名常量(具有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

也就是说,array1array2 是显式形状自动对象。出于许多目的,实际上并不需要命名常量。

但是,除了数组大小之外,当然不允许以下内容。

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

【讨论】:

    【解决方案2】:

    如果要将数组的大小定义为运行时,则需要动态分配。所有参数(常量)都必须定义为编译时间。

    【讨论】:

    • @kirikoumath,我很高兴为您提供帮助。记得接受答案,这样有同样问题的人可以很容易地找到它。如果您还有其他问题,请尽管提问。
    【解决方案3】:

    parameter 的值是在编译时设置的。

    声明如

    integer, parameter :: number_of_widgets = numwidge
    

    要求在编译时知道numwidge,在声明的rhs上遇到它之前确实知道。

    【讨论】:

    • 所以我可以这样做:INTEGER, PARAMETER (n = variable) 其中variable 是从输入文件中读取的值吗?
    • @kirikoumath 仅当 variable 也是常量时。
    • @AlexanderVogt 如何定义从输入文件读取的常量变量?
    • @你不能。 (至少在运行时)。但是,您可以使用预处理器来定义variable
    • @AlexanderVogt 我想念教堂的config constconfig param
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 2023-02-03
    相关资源
    最近更新 更多