The block IF statement executes one of two or more sequences of statements, depending on the value of a logical expression.
IF (e) THEN
Parameter |
Description |
e |
A logical expression |
The block IF statement evaluates a logical expression and, if the logical expression is true, it executes a set of statements called the IF block. If the logical expression is false, control transfers to the next ELSE, ELSE IF, or END IF statement at the same IF-level.
The IF level of a statement S is the value n1-n2, where n1 is the number of block IF statements from the beginning of the program unit up to the end, including S; n2 is the number of END IF statements in the program unit up to, but not including, S.
Example: In the following program, the IF-level of statement 9 is 2-1, or, 1
IF ( X .LT. 0.0 ) THEN MIN = NODE END IF ... 9 IF ( Y .LT. 0.0 ) THEN MIN = NODE - 1 END IF
The IF-level of every statement must be zero or positive. The IF-level of each block IF, ELSE IF, ELSE, and END IF statement must be positive. The IF-level of the END statement of each program unit must be zero.
An IF block consists of all the executable statements following the block IF statement, up to, but not including, the next ELSE, ELSE IF, or END IF statement that has the same if level as the block IF statement. An IF block can be empty. In the following example, the two assignment statements form an IF block:
IF ( X .LT. Y ) THEN M = 0 N = N+1 END IF
Execution proceeds as follows:
The logical expression e is evaluated first. If e is true, execution continues with the first statement of the IF block.
If e is true and the IF block is empty, control is transferred to the next END IF statement with the same IF level as the block IF statement.
If e is false, control is transferred to the next ELSE IF, ELSE, or END IF statement with the same IF level as the block IF statement.
If the last statement of the IF block does not result in a branch to a label, control is transferred to the next END IF statement that has the same IF level as the block IF statement preceding the IF block.
Control cannot jump into an IF block from outside the IF block.
IF ( L ) THEN N=N+1 CALL CALC ELSE K=K+1 CALL DISP END IF
Example 2: IF-THEN-ELSE-IF with ELSE-IF:
IF ( C .EQ. 'a' ) THEN NA=NA+1 CALL APPEND ELSE IF ( C .EQ. 'b' ) THEN NB=NB+1 CALL BEFORE ELSE IF ( C .EQ. 'c' ) THEN NC=NC+1 CALL CENTER END IF
Example 3: Nested IF-THEN-ELSE:
IF ( PRESSURE .GT 1000.0 ) THEN IF ( N .LT. 0.0 ) THEN X = 0.0 Y = 0.0 ELSE Z = 0.0 END IF ELSE IF ( TEMPERATURE .GT. 547.0 ) THEN Z = 1.0 ELSE X = 1.0 Y = 1.0 END IF