Pointers in Fortran

Fortran supports pointers, allowing you to pass references to values and variables within your program.

program pointers
    implicit none
    integer :: i
    
    i = 1
    print *, "initial:", i
    
    call zeroval(i)
    print *, "zeroval:", i
    
    call zeroptr(i)
    print *, "zeroptr:", i
    
    print *, "pointer:", loc(i)

contains

    subroutine zeroval(ival)
        integer, intent(inout) :: ival
        ival = 0
    end subroutine zeroval

    subroutine zeroptr(iptr)
        integer, pointer :: iptr
        iptr = 0
    end subroutine zeroptr

end program pointers

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:

$ gfortran pointers.f90 -o pointers
$ ./pointers
initial:           1
zeroval:           1
zeroptr:           0
pointer:    140732920751228

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.