0

I am testing a procedure for which I wrote a subroutine in which I declared a parameter a

Module f1
implicit none
contains
Subroutine function1 (var)
implicit none
integer, intent(in) :: var
integer, parameter :: a=3.5

print*, "initial var is ", var 
end Subroutine function1
end module f1

Now, I called this subroutine in my main program in the following way

program f2
use f1, only: function1
implicit none
integer :: y
integer :: z,x
integer :: a
y=2
x=1
CALL function1 (x)
z=x+y+a
print*, "My sum is ", z
end program f2

The value of my parameter a gets changed. When I compiled and linked my program, I got the following output

initial var is            1
 My sum is    543297931

When I printed the value of a, I got

 My parameter is    543297928

I am unable to understand why my value gets changed. I also checked about some common procedures which cause such issues but I did not get any hint.

francescalus
  • 30,576
  • 16
  • 61
  • 96
Agni
  • 147
  • 5
  • Do you think that the value of `a` in the main program is related to that constant in the subroutine (!) `function1`? Largely you have the same as [this problem](https://stackoverflow.com/q/42024559/3157076) but in the other direction. – francescalus Jul 23 '18 at 11:58
  • Does this mean that `a` is not global and I should define it in a module instead of that subroutine? I got the correct value when I defined it in the above module. Thanks – Agni Jul 23 '18 at 12:04
  • Yes, the `a` of `function1` is local to that subroutine, and the `a` of the main program is local there. Values aren't shared. Further, the program's `a` isn't a constant (and hasn't a defined value when you reference it). And yes, if you want the same constant "shared" then you can do that with a module. – francescalus Jul 23 '18 at 12:07
  • What if I do not write my subroutine inside the module. I write an independent one and call it in the main program? It is still local. Actually I saw several procedures which were based on subroutines only. But the values didn't change when those subroutines were called. I am sorry I am not giving an example here but I just want to confirm if this can happen. – Agni Jul 23 '18 at 12:11
  • `subroutine function1(); use a_mod, only : a; end subroutine`, for example? – francescalus Jul 23 '18 at 12:28
  • 1
    Ok, I got it. Those parameters are meant to work only inside that subroutine. I can not access them outside their scope. Thanks for the help. – Agni Jul 24 '18 at 05:42

0 Answers0