Fortran PARAMETER variable initialized from input

前端 未结 3 1951
谎友^
谎友^ 2020-12-11 22:01

In Fortran, is the PARAMETER attribute set at runtime or compilation time? I was wondering if I can pass in the size the of the array at run time and have this

相关标签:
3条回答
  • 2020-12-11 22:39

    You need dynamic allocation if the size of your array is to be defined as runtime. All parameter (constants) must be defined as compiling time.

    0 讨论(0)
  • 2020-12-11 22:46

    Yes, as repeatedly answered, a named constant (an object with the parameter attribute) must have its initial value "known at compile time". However, as you talk about the size of arrays I'll note something else.

    When declaring the shape of an array there are many times when the bounds needn't be given by constant expressions (of which a simple named constant is one example). So, in the main program or a module

    implicit none
    ...
    integer, dimension(n) :: array  ! Not allowed unless n is a named constant.
    end program
    

    the n must be a constant. In many other contexts, though, n need only be a specification expression.

    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
    

    That is, array1 and array2 are explicit shape automatic objects. For many purposes one doesn't really need a named constant.

    Beyond the array size, the following is certainly not allowed, though.

    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
    
    0 讨论(0)
  • 2020-12-11 22:47

    The value of a parameter is set at compile time.

    A declaration such as

    integer, parameter :: number_of_widgets = numwidge
    

    requires that numwidge be known at compile time, indeed known before it is encountered on the rhs of the declaration.

    0 讨论(0)
提交回复
热议问题