0

Hi I have a question regarding a problem I encountered. I did resolve the problem, but I am originally a Python user and was wondering why Fortran would do certain things. The following happened while executing a code like this.

module formula
  contains
  
  function f1(a) result(c)
    real :: a, b, c
    
    b = a + 2
    c = c + b
  end function
end module

module use
  use formula

  contains
  
  function f2(x) result(y)
      real :: x, y
  
      y = f1(x) + f1(x)
  end function
end module

The issue persists when calculating y, caused by not defining c in f1. The following happens when we give x=1, thus, y = f(1) + f(1). One would expect that it would not compile (c has no value yet) or just 6 would roll out. However, the answer is 9. This is because it seems that Fortran takes the c value from the first created f1 for the second f1, as it is not defined yet. It seems to work this way since, when I declare c = 0 in f1, the issue was resolved and y would be 6.

This is very weird to me, as the second time we call f1 the system should not take the old memory since the first f1 is completed and closed (but I guess not), it retrieves the old c and continues with it. Why does Fortran take the 'old' c and not create new memory for a new f1 with a new c? This seems odd to me as I would expect to have only the result of the first f1 and then continue to the second f1. By moving on I'd expect to have the contents of the first f1 to be lost.

Is there a page somewhere on the web explaining this or could one explain this to me?

n.b. the usage of c = c + b is useless in this instance. But it is used for this for simplicity, in the original code I have a loop adding a calculation to it.

  • Welcome, please take the [tour]. Use tag [tag:fortran] for Fortran questions. Fortran 90 is just one very old revision of the standard. Also, please do not use the javascript snippet feature for code samples in other languages. – Vladimir F Героям слава Mar 11 '22 at 14:00
  • If the value is undefined, you are not allowed to use it. That does not mean, that the code shall not compile. See undefined behaviour in some other programming languages. – Vladimir F Героям слава Mar 11 '22 at 14:02
  • 1
    In the linked https://stackoverflow.com/questions/57558684/does-fortran-have-undefined-behavior see the reference to **"A reference is permitted only if the variable is defined."** (the result variable is also a variable). If you reference it anyway, anything may happen. If the stacks align, it is quite likely that the stack frame of the last function instance was not overwritten and you are accessing the garbage value from the last time the stack frame was used. If you run some other function in the meantime, you may get complete garbage. – Vladimir F Героям слава Mar 11 '22 at 14:03

0 Answers0