0

I am having some issues calling subroutines. First of all, am I allowed to call a subroutine within an IF statement?

IF (...) THEN
  ...
ELSE
  CALL sub1(...)
END IF

Second question. Sub1 calls sub2 within it self. Then sub2 has an input from the main program, lets say x.

MODULE mod1
  ...
CONTAINS

  SUBROUTINE sub1(w)

    IMPLICIT NONE
    INTENT(OUT) :: w
    REAL :: x, z

    CALL sub2(x, z)

    w = z + 1

  END SUBROUTINE sub1

  SUBROUTINE sub2(x, z)

    IMPLICIT NONE      
    INTENT(IN) :: x
    INTENT(OUT) :: z

    z = x + 1

  END SUBROUTINE sub2

END MODULE mod1

PROGRAM prog

  USE mod1
  IMPLICIT NONE

  IF (...) THEN
    ...
  ELSE
    x = y
    CALL sub1(w)
    x = w + y
  END IF

END PROGRAM prog

NOTE: The addition between variable isn't the exact mathematical operation taking place

Basically every variable depends on each other, but the x = y is the initial condition which I think is the only way this could work. It seems that the sub2 isn't picking up on the initial x = y, which then gives its value to sub1, when called from sub1. So maybe I don't understand how the variables are being passed around. The errors I am getting is not with compiling but a run time error which leads me to the line where I call sub2 within sub1. Any help is much appreciated.

Dtaai
  • 15
  • 1
  • 4
  • Please do not make changes that make existing answers nonsense. If you have a new question with a new code ask a new question. Or first ask someone ho answered in a comment if you are unsure about his answer. – Vladimir F Героям слава Feb 27 '17 at 09:48
  • Ok, I reverted to your change if you say it is in your real code, but: 1. Never post such "simplified" code. 2. read the answer you got and the answers to the question I linked. The `x` and `y` in the subroutine are local variables. It does not matter if they are declared implicitly or you declare them with `real x,y`. They are still local variables of the subroutine. – Vladimir F Героям слава Feb 27 '17 at 09:53
  • Didn't mean to cause confusion. I understand now, thank you. – Dtaai Feb 27 '17 at 14:24

1 Answers1

0

Please use implicit none at the beginning of all your programs and modules (only USE statements go before it), and then declare all variables explicitly.

While it's perfectly fine to call your subroutines the way you did, you have to take into consideration the scope of the variables.

In your example, sub1 does not have access to the main program's x and y as they're local to the main program.

chw21
  • 7,970
  • 1
  • 16
  • 31
  • Sorry, just edited it. I do have it on my real code though. In this case sub1 wouldnt need x or y, but will need z from sub2, which needs x from the main program. – Dtaai Feb 27 '17 at 09:47
  • Please have a look at my answer to the question I linked. The x and y are not the same x and y in the subroutine and in the main program. – Vladimir F Героям слава Feb 27 '17 at 09:50