Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing constant with variable's value

Tags:

fortran

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 at the line marked (*). Is there a way to set the value of a constant with a value coming outside that function?

like image 608
thetux4 Avatar asked Nov 28 '22 03:11

thetux4


1 Answers

You can't declare "b" as a parameter since 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 are sure to declare all variables. Also to place your procedures into a module and "use" that module so that the interface is known to the caller. As 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
like image 133
M. S. B. Avatar answered Dec 09 '22 09:12

M. S. B.