Skip to content

FOR002 loop-order-not-column-major ​

warning opt-in

The innermost loop runs over a non-leading array dimension while an outer loop runs over the leading one.

Why ​

Fortran stores arrays column-major: a(i, j) and a(i+1, j) are adjacent in memory, a(i, j) and a(i, j+1) are a whole column apart. The innermost loop must run over the leftmost subscript to walk memory with stride 1; the swapped order makes every access a cache miss and stops vectorisation. Reported when, for most array references of the innermost loop, its index is in a later dimension and the enclosing loop's index in the first.

Reported ​

fortran
do i = 1, ni
  do j = 1, nj
    a(i, j) = b(i, j) + c(i, j)
  end do
end do

Preferred ​

fortran
do j = 1, nj
  do i = 1, ni
    a(i, j) = b(i, j) + c(i, j)
  end do
end do

Suppressing ​

For one occurrence, with the reason on the same line (or alone on the line before the statement):

fortran
! fobis: ignore[FOR002] <why this occurrence is fine>

For the whole project, ignore = FOR002 in the fobos [lint] section.

References ​

Sections of the shipped knowledge packs behind this rule:

  • hpc-practice:fortran-practice#array-loop-ordering-column-major (fobis kb show hpc-practice:fortran-practice#array-loop-ordering-column-major)