In Fortran, is it possible for declaration statements for variables to refer to previously-declared variables? For example, when I try the following:
PROGRAM test3
IMPLICIT NONE
INTEGER :: a=2286
INTEGER :: b=a/3
WRITE(*,*) a, b
END PROGRAM test3
I get a compile-time error message:
test3.f90:5.16:
INTEGER :: b=a/3
1
Error: Parameter 'a' at (1) has not been declared or is a variable, which
does not reduce to a constant expression
On the other hand, if I assign b to a/2 in a statement separate from the declaration of b, it compiles and runs fine:
PROGRAM test3
IMPLICIT NONE
INTEGER :: a=2286
INTEGER :: b
b=a/3
WRITE(*,*) a, b
END PROGRAM test3
which gives me the correct output:
2286 762
Why is this the case--that previously-declared variables cannot be included in declaration statements of new variables? Am I doing something wrong? Or is this just a "Fortran fact of life"?
Thank you very much for your time!
The error message is pretty explicit. Initializers used in variable declarations have to be constant values. In your example, a
is not a constant.
It should work like this:
PROGRAM test3
IMPLICIT NONE
INTEGER, PARAMETER :: a=2286
INTEGER :: b=a/3
WRITE(*,*) a, b
END PROGRAM test3
because then a
is a constant.