Fortran Execution Control If construct


Example

The if construct (called a block IF statement in FORTRAN 77) is common across many programming languages. It conditionally executes one block of code when a logical expression is evaluated to true.

[name:] IF (expr) THEN
    block
[ELSE IF (expr) THEN [name]
    block]
[ELSE [name]
   block]
END IF [name]

where,

  • name - the name of the if construct (optional)
  • expr - a scalar logical expression enclosed in parentheses
  • block - a sequence of zero or more statements or constructs

A construct name at the beginning of an if then statement must have the same value as the construct name at the end if statement, and it should be unique for the current scoping unit.

In if statements, (in)equalities and logical expressions evaluating a statement can be used with the following operators:

.LT.  which is <   ! less than
.LE.           <=  ! less than or equal
.GT.           >   ! greater than
.GE.           >=  ! greater than or equal
.EQ.           =   ! equal
.NE.           /=  ! not equal
.AND.              ! logical and
.OR.               ! logical or
.NOT.              ! negation

Examples:

! simplest form of if construct
if (a > b) then
    c =  b / 2
end if
!equivalent example with alternate syntax
if(a.gt.b)then
   c=b/2
endif

! named if construct
circle: if (r >= 0) then
    l = 2 * pi * r
end if circle

! complex example with nested if construct
block: if (a < e) then
    if (abs(c - e) <= d) then
        a = a * c
    else
        a = a * d
    end if
else
    a = a * e
end if block

A historical usage of the if construct is in what is called an "arithmetic if" statement. Since this can be replaced by more modern constructs, however, it is not covered here. More details can be found here.