Is there a way to read in a variable and then set it as a parameter?

Dear all,

A quick question, in Fortran is it possible to read in a variable first, then declare it as parameter?
Like

integer :: n
read (6,*)  n

then set n as a parameter?

Thank you very much!

I mean sometimes this may be useful because if I wanted to initialize the array with size n, only once in the whole problem, and this n is actually an input which can be set by the user in a txt file.
By setting some values as parameter, perhaps the speed could be increased a little bit.

I know it may not be possible.
So perhaps a work around, is to use R or something to place the value of n set by the user, say 100, to
a text line, like
integer, parameter : : n = 100
then copy this line to the program code file.
so that n is set in the code as paramter. then compile the program again, and then run,

This is not possible. As far as I remember, a ‘variable’ with a parameter attribute is not even a variable :wink:

If you need to have read only variables, you can put them in a module and give them the protected attribute

module constants
  integer, protected, public :: n

  contains
  subroutine read_n()
    read(6,*) n
  end subroutine read_n

end module constants
2 Likes

Thank you! I learned a new trick today, protected, nice! :100:

Given that memory is cheap, and if you know n is bounded, you could just declare a fixed-size array of size 1000000 up front and only use the first n elements.

This pattern was commonly used in the F77 days. Today you can use allocatable arrays instead. I thought you are using the /heap-arrays0 compiler flag anyways?

I doubt the overhead of recompiling, just to insert a line like

integer, parameter : : n = 100

will be amortized by the lower runtime.

1 Like