Variable declaration, initialization, and types in Fortran
Fortran variables can be scoped to a program, module, subroutine, or function. They can be implicitly declared based on their first letter (I-N are integers, all others are floats) but this practice is highly discouraged. It’s better to explicitly declare variables as an intrinsic data type like INTEGER, REAL, COMPLEX, LOGICAL, or CHARACTER.
You should always use `implicit none
` to disable Fortran’s implicit typing behavior. It’s a hangover from an old version of Fortran that implicitly typed all variables beginning with the letters ‘i’ through ‘n’ as being integers, and all others as real numbers (floats).
Variable names in Fortran consist of 1-6 characters chosen from the letters a-z and the digits 0-9. The first character must be a letter. It does not distinguish between upper and lower case, and assumes all input is upper case, but most compilers will accept lower case.
program example
! Add this line to disable all implicit typing defaults
implicit none
! Declare all variables at the top of the file
INTEGER :: num
DOUBLE PRECISION :: dblnum
REAL :: rlnum
COMPLEX :: cnum
CHARACTER(len=15) :: str
LOGICAL :: flag
LOGICAL :: isVerified, isValid
num = 123
dblnum = 2.364
rlnum = 67.21
cnum = (3, 5)
str = "Hello Stranger"
isValid = .TRUE.
isVerified = .FALSE.
! Note that the 'flag' variable is NOT initialized
print *, num ! Output: 123
print *, dblnum ! Output: 2.3640000820159912
print *, rlnum ! Output: 7.2099991
print *, cnum ! Output: (3.00000000,5.00000000)
print *, str ! Output: Hello Stranger
print *, flag ! Output: F
print *, isValid ! Output: T
print *, isVerified ! Output: F
end program example