Search code examples
makefilefortran

Conditional parameter declaration in Fortran


I'm shopping for ideas on how to implement a "conditional" parameter declaration. The problem is, in essence, that I have a project in which parameters are declared in a separate module, and the main program and all the other modules in the project load the parameter module. The problem is that I would like to be able to run the same project with two different sets of parameter values without having to modify the program and related files much (it would take too much time at this point).

The current program I have, with only one set of parameters, is the following. First the main program:

program main

    use myparams
    implicit none

    ! Execute program, call modules, etc...
    print *, 'Value for x =', x

end program main

Then a module with the parameters:

module myparams

    implicit none
    integer,parameter :: set = 1
    real,parameter    :: x = 2.0
    
end module myparams

Essentially, I would like to have x = 3.0 whenever compiling a case in which set = 2, for example. I, of course, know that I cannot use a conditional in the variable declaration block, so I'm looking for alternatives. Maybe at compilation? In a Makefile?

I have two separate projects (different folders, so duplicated source files), one in which x = 2.0 and another one in which x = 3.0, but any changes in other parts of the program require going back and forth and updating the same code in both projects... so not ideal.


Solution

  • A constant expression's evaluation can depend conditionally on the value of another constant, using elemental intrinsic functions.

    A popular choice for expression value selection is the MERGE function, but other evaluations are possible:

      implicit none
    
      integer, parameter :: set = 2
      real, parameter :: x = MERGE(3., 2., set==2)
      real, parameter :: y = x - COUNT([set==2])
    
      print '(F2.0)', x, y
    
    end program