BLOCK construct (Fortran 2008)

The BLOCK construct defines an executable block that can contain declarations.

Syntax

Read syntax diagramSkip visual syntax diagram BLOCK_statement
Read syntax diagramSkip visual syntax diagramspecification_part
Read syntax diagramSkip visual syntax diagram statement_block
Read syntax diagramSkip visual syntax diagram END_BLOCK_statement

Execution of a BLOCK construct causes evaluation of its specification_part followed by execution of its statement_block.

BLOCK_statement
See BLOCK (Fortran 2008) for syntax details.
END_BLOCK_statement
See END (Construct) for syntax details.

A local variable of a BLOCK construct within a pure subprogram cannot have the SAVE attribute.

The specification part of the BLOCK construct must not contain COMMON, EQUIVALENCE, IMPLICIT, INTENT, NAMELIST, OPTIONAL, statement function, or VALUE statements.

The saved entity list of a SAVE statement in a BLOCK construct must not specify a common block name.

Examples

Example 1: The following example shows that a BLOCK construct can be specified with an optional name and nested within another BLOCK construct.
PROGRAM MyProgram
  INTEGER :: a
  
  add1 : BLOCK            
    INTEGER :: res1
    res1 = a + 1
    ! The BLOCK statement has no BLOCK_construct_name
    BLOCK
      INTEGER :: res2
      res2 = res1 + 1
    END BLOCK
  ! The END BLOCK statement must have the same BLOCK construct name 'add1'         
  END BLOCK add1    
END PROGRAM MyProgram     
Example 2: You cannot transfer control from outside a BLOCK construct to inside the BLOCK construct, except for the return from a procedure call inside the construct. For example:
PROGRAM main
  INTEGER :: a
  
  a = 5
  BLOCK
    INTEGER :: b
    b = a + 2
    ! Program control is returned from a procedure call inside the BLOCK construct
    CALL Sub(b)
  END BLOCK
END PROGRAM main

SUBROUTINE Sub(B)
  INTEGER :: b
  
  b = b * b
  PRINT *, b
END SUBROUTINE Sub
Example 3: The following example shows how an unconditional GOTO statement is used to exit a BLOCK construct.
   PROGRAM MyProgram 
      INTEGER :: i
      i = 100

     BLOCK
       INTEGER :: i
       i = 1
       ! Before the BLOCK construct is exited, local allocatables are
       ! deallocated, and local finalizable objects are finalized.
       GOTO 10          
       i = i + 1
     END BLOCK

10   PRINT *, i
   END PROGRAM MyProgram

Related information