Using Fortran Whole‑Array Operations and Array Slicing for Loop‑Free Code
Fortran lets you apply operators to whole arrays or slices, avoiding loops, but requires conformable shapes and proper procedure intent.
01 Jul 2025, 18:18 UTC

Quick answer
Fortran 90 and later let you apply arithmetic operators and intrinsics to whole arrays or to selected sections, eliminating the need for explicit DO loops when the arrays have the same shape.
Worked example
Declare two rank‑1 arrays, compute a scaled sum, and extract every other element with a slice.
program demo
implicit none
integer, parameter :: n = 10
real :: A(n), B(n), C(n), D(:)
! initialize arrays
A = [(real(i), i=1,n)]
B = [(real(2*i), i=1,n)]
! whole‑array operation: C = A + 2*B
C = A + 2.0 * B
! array section: every second element from index 2 to n
D = A(2:n:2)
print *, 'C =', C
print *, 'D =', D
end program demo
To build and run the example with GNU Fortran:
- Save the code to
demo.f90in a directory where you have write permission. - Compile with
gfortran -std=f2008 -Wall -O2 demo.f90 -o demo. The-std=f2008flag ensures the compiler accepts whole‑array syntax and array slicing. - Execute
./demo. The program prints the computed arrays.
Limits and common mistakes
Conformance requirement
Whole‑array operators require the operands to have identical shape. If B is declared with a different length, the compiler emits an error such as “non‑conformable arrays” at compile time, preventing silent runtime mismatches.
Array sections are read‑only views
An expression like A(2:n:2) returns a section that, in most contexts, cannot be assigned to unless it is passed to a procedure with the proper intent. Attempting to modify a section directly, e.g. A(2:n:2) = 0.0, is allowed only when the section appears on the left‑hand side of an assignment and the compiler can determine it is writable; otherwise you may get a compile‑time error or unexpected results.
Procedure interfaces
When passing a section to a subroutine, the dummy argument must be declared with matching rank and either explicit shape, assumed‑shape (:) or assumed‑size (*). Mismatched rank or missing INTENT(INOUT) leads to warnings or errors.
Step value restrictions
The stride in a triplet low:high:step must be a non‑zero positive integer. A step of zero or a negative value is rejected as invalid syntax.
Performance considerations
Compilers may create temporary arrays for complex expressions. Using contiguous data, the CONTIGUOUS attribute, or calling intrinsics like MATMUL can reduce overhead.
How to verify the behavior
- Change
Bto size 4 while keepingAsize 10, recompile, and observe the compile‑time shape‑mismatch error. - Try to assign to a slice inside a subroutine without
INTENT(INOUT); the compiler will flag the intent mismatch. - Use a negative step, e.g.
A(10:2:-1), and confirm the compiler reports a syntax error.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.