Fortran Execution Control WHERE construct


Example

The where construct, available in Fortran90 onwards represents a masked do construct. The masking statement follows the same rules of the if statement, but is applied to all the elements of the given array. Using where allows operations to be carried out on an array (or multiple arrays of the same size), the elements of which satisfy a certain rule. This can be used to simplify simultaneous operations on several variables.

Syntax:

[name]: where (mask)
    block
[elsewhere (mask)
    block]
[elsewhere
    block]
end where [name]

Here,

  • name - is the name given to the block (if named)
  • mask - is a logical expression applied to all elements
  • block - series of commands to be executed

Examples:

! Example variables
real:: A(5),B(5),C(5)
A = 0.0
B = 1.0
C = [0.0, 4.0, 5.0, 10.0, 0.0]

! Simple where construct use
where (C/=0)
    A=B/C
elsewhere
    A=0.0
end

! Named where construct
Block: where (C/=0)
    A=B/C
elsewhere
    A=0.0
end where Block