Search code examples
fortraninitializationuser-input

Fortran Command Line Input In Specification Part


I am new to fortran and I am having issues trying to pass in a argument via command line. For instance my working code has the following lines:

!experimental parameters
real (kind=8), parameter :: rhot                =1.2456
!density of top fluid
real (kind=8), parameter :: rhob                = 1.3432
!density of bottom fluid
real (kind=8), parameter :: rhof                = (rhot-rhob)
!generic function of rhot rhob

And I would like to hand them in via:

./fulltime_2009_05_15_Fortran9 [Value rhot] [Value rhob]

using something like:

call get_command_argument(1,input1)
call get_command_argument(2,input2)
read(input1,*) rhot
read(input2,*) rhob

The issue is, I declare parameters like rhof that depend on the inputted values. So I would like to have the user inputted values applied immediately so that all dependent parameters can use those values. However, if modify my code to be:

real (kind=8) :: rhot,  rhoB
call get_command_argument(1,input1)
call get_command_argument(2,input2)
read(input1,*) rhot
read(input2,*) rhob
real (kind=8), parameter :: rhof    = (rhot-rhob)

I get the error: A specification statement cannot appear in the executable section.

Any thoughts or suggestions for how I could address this issue?


Solution

  • A compile time constant (parameter) cannot be changed by command line arguments. It is fixed at compile time.

    This code:

    real (kind=8) :: rhot,  rhoB
    real (kind=8) :: rhof
    call get_command_argument(1,input1)
    call get_command_argument(2,input2)
    read(input1,*) rhot
    read(input2,*) rhob
    rhof    = (rhot-rhob)
    

    would compile fine. But you cannot have a variable declaration after a normal statement.

    You could have

    real (kind=8) :: rhot,  rhoB
    call get_command_argument(1,input1)
    call get_command_argument(2,input2)
    read(input1,*) rhot
    read(input2,*) rhob
    
    block
      real (kind=8) :: rhof    = (rhot-rhob)
    

    in Fortran 2008, but you cannot define a compile-time constant using a non-constant expression.

    Some programming langauges do allow a type of constants that are set during the configuration of the run and are fixed thereafter. Fortran is not one of them.