Exploring pointers in Fortran: When and how to use them

The converse is also true for pointers. For example, in your code above, the executable statement within the nested loop must be executed serially, ensuring that the result memory location is updated before the next access to the input arrays, just in case the C[] array has any memory overlaps with either A[] or B[].

In fortran, the compiler would be free to optimize the loops because the array C(:,:) is not allowed to alias the other dummy arguments A(:,:) and B(:,:). This restriction is the responsibility of the programmer to enforce. That means, the compiler is free to make use of registers or GPU memory or any other optimization approach and the memory accesses and stores can be reordered and/or delayed as much as the compiler would like. This is not a recent change to the language, this alias restriction has been in fortran since before f77. More recent versions of C and other C-like languages have introduced pragmas and other workarounds to try to mimic the fortran convention and to allow similar optimizations, but that demonstrates the disadvantage of using wild pointers in languages.

Pointers in fortran can only point to objects with the target attribute. Thus, even when using pointers in fortran, the compiler already knows more about the optimization possibilities than in a wild-pointer language.

Fortran also has allocatable arrays that can be used in many situations that would require pointers in other languages, including data structures such as trees and linked lists. This also avoids the wild-pointer alias problems when using these data structures in fortran.

1 Like