Variables in Fortran
Our first example demonstrates how to declare and use variables in Fortran. Here’s the full source code:
In Fortran, variables must be explicitly declared before they can be used. The implicit none
statement at the beginning of the program turns off implicit typing, which is a good practice to avoid accidental variable declarations.
We can declare variables of different types:
character(len=7) :: a = "initial"
declares a character variable of length 7 and initializes it.integer :: b = 1, c = 2
declares two integer variables and initializes them.logical :: d = .true.
declares a logical variable and initializes it to true.integer :: e
declares an integer variable without initialization. In Fortran, uninitialized variables have undefined values, so it’s a good practice to always initialize variables before use.character(len=5) :: f = "apple"
declares another character variable and initializes it.
To run the program, save it as variables.f90
and compile it using a Fortran compiler, then run the resulting executable:
Note that the output of uninitialized variables (like e
in this case) is compiler-dependent and may not always be zero.
Fortran doesn’t have a direct equivalent to Go’s :=
syntax for declaring and initializing variables in one line within functions. In Fortran, variables are typically declared at the beginning of the program or subroutine.
Now that we’ve seen how to declare and use variables in Fortran, let’s move on to explore more features of the language.