Perhaps similar questions have been asked before. But I dare to ask again, LOL.
Usually in the code, we read in variables from a file, say a variable called AAA.
So we can use the same code without re-compile and build again each time the variable AAA changes.
Now I am just curious, if this AAA is read in once, and never change in the code. Can we make it a CONSTANT?
I know we have parameter already, but this is for setting a parameter to a fixed number which is known before runtime.
While the CONSTANT is know at runtime. However since AAA is CONSTANT, it can only be set value for only once. So perhaps this can help the compiler to do some runtime optimization?
I mean, you know so then, for example, if I have another variable BBB which is
the compiler once know the CONSTANT value of AAA, it knows BBB is also a CONSTANT, and BBB’s value can be calculated when it is first called, and then stored. So no need to repeatedly calculate BBB anymore in the rest of the code.
Things like that may help further speedup the code perhaps.
btw,
is there similar idea in C/C++ or Python or something?
The Fortran analog is to associate the constant to an expression:
program main
implicit none
integer, parameter :: dp = kind(1.0d0)
real(kind=dp) :: x
print*,"enter a double"
read (*,*) x
associate (y => (x))
print*,"y =",y
! if line below uncommented, get gfortran error
! Error: 'y' at (1) associated to expression cannot be used in a variable definition context (assignment)
y = 2*y
end associate
end program main
A variable associated to another variable is not a constant, so the following code, with y => x instead of y => (x), compiles:
program main
implicit none
integer, parameter :: dp = kind(1.0d0)
real(kind=dp) :: x
print*,"enter a double"
read (*,*) x
associate (y => x)
print*,"y =",y
y = 2*y
print*,"y =",y
end associate
end program main