Initializing a constant with a variable value

program main real, parameter :: a = 1 !real :: a !a=1 res = func(a) write(*,*) res end program main function func(a) real, parameter :: b=a+1 !(*) func = b return end function func 

My compiler complains about the line marked with (*). Is there a way to set a constant value with a value that is outside the scope of this function?

+4
source share
2 answers

You cannot declare β€œb” as a parameter, because its value is not constant at compile time, since it depends on the function argument.

It is a good idea to use "implicit none" so that you must declare all variables. Also put your procedures in a module and β€œuse” this module so that the interface is known to the caller. How in:

 module my_funcs implicit none contains function func(a) real :: func real, intent (in) :: a real :: b b = a + 1 func = b return end function func end module my_funcs program main use my_funcs implicit none real, parameter :: a = 1 real :: res res = func(a) write(*,*) res end program main 
+17
source

@M. SB's answer is great if runtime initialization is acceptable to you. If you really need the Fortran parameter , which is set at compile time, you can do it like this:

 program main implicit none real, parameter :: a = 1.0 real :: res res = func() write(*,*) res contains function func() real, parameter :: b = a + 1.0 real :: func func = b end function func end program main 

I suspect part of the confusion is due to differences in language. Often a β€œparameter” is used to indicate a function argument, but in Fortran it is never used that way. Instead, it means something similar to const in C / C ++. So, it is not clear to me from your question whether you really need the Fortran parameter or not.

In my example above, the parameter a is known inside func through the host association, which is Fortran lingo for nested areas. You can also do this with modules using a usage association, but this is a bit more verbose:

 module mypars implicit none real, parameter :: a = 1.0 end module mypars module myfuncs implicit none contains function func() use mypars, only: a real, parameter :: b = a + 1.0 real :: func func = b end function func end module myfuncs program main use myfuncs, only: func implicit none real :: res res = func() print *, res end program main 
+8
source

Source: https://habr.com/ru/post/1391147/


All Articles