View Full Version : FORTRAN: Basic Question about declaring variables
Saladsamurai
Jun5-11, 08:51 PM
If you call a subroutine from the MAIN code, is it standard to declare the variables used in the subroutine in the subroutine itself or in the main code? My gut tells me the former, but the horrendously written code before me tells me the latter.
Any thoughts?
SteamKing
Jun5-11, 09:59 PM
Guess what? Variables can be declared in both the main routine and the subroutine!
Check it:
Program Test
Real x, y, ans
Call Calc (x, y, ans)
End
C
Subroutine Calc (A, B, C)
Real A, B, C
C = A + B
RETURN
END
Saladsamurai
Jun5-11, 10:02 PM
Guess what? Variables can be declared in both the main routine and the subroutine!
Check it:
Program Test
Real x, y, ans
Call Calc (x, y, ans)
End
C
Subroutine Calc (A, B, C)
Real A, B, C
C = A + B
RETURN
END
Hi SteamKing :smile:
I guess my question is more along the lines of "what is better programming" and not so much which one works. Is it common to declare them in the MAIN and not in the sub?
Variables should be declared in both places. There really are two sets of variables: the actual parameters that are used in your main routine, and the formal parameters that are used in your subroutine.
Saladsamurai
Jun5-11, 10:59 PM
Variables should be declared in both places. There really are two sets of variables: the actual parameters that are used in your main routine, and the formal parameters that are used in your subroutine.
Ok. But if the variable is not used in Main at all and is only used in various sub routines, then isn't weird to declare it in Main? If not 'weird' ... confusing?
You're using a variable when you call the subroutine, as in call Calc(x, y, ans) -- SteamKing's example.
I'm assuming that you have variables in the call to the subroutine or function, rather than literals (i.e., constants of some kind).
vBulletin® v3.8.7, Copyright ©2000-2012, vBulletin Solutions, Inc.