Pointers in Fortran
Fortran supports pointers, allowing you to pass references to values and variables within your program.
We’ll show how pointers work in contrast to values with two subroutines: zeroval
and zeroptr
. zeroval
has an integer
parameter, so arguments will be passed to it by value. zeroval
will get a copy of ival
distinct from the one in the calling program.
zeroptr
in contrast has an integer, pointer
parameter, meaning that it takes an integer pointer. Assigning a value to a pointer changes the value at the referenced address.
The loc()
function is used to get the memory address of a variable, which is similar to the &
operator in other languages.
To compile and run this Fortran program:
zeroval
doesn’t change the i
in the main program, but zeroptr
does because it has a reference to the memory address for that variable.
Note that Fortran’s handling of pointers is somewhat different from languages like C or Go. In Fortran, pointers are typically used with allocatable objects or to create alias names for variables. The example above is a simplified demonstration to show the concept of passing by reference vs passing by value.