C/C++ and Fortran

 View Only

Internal procedures as actual arguments or procedure pointer targets

By Archive User posted Wed October 30, 2013 11:20 PM

  

Originally posted by: Yvonne Ma


The Fortran 2008 standard relaxes some rules for internal procedures. Procedure pointers can now point to internal procedures. In addition, you can use internal procedures and pointers to internal procedures as actual arguments.  Because an internal procedure has access to the variables of its host procedure, procedure pointers to an internal procedure can only be used before the host procedure completes its execution.

 

Here is an example of a procedure pointer to an internal procedure:

 

module m
  implicit none
  abstract interface
    subroutine int_printer(i)
      integer, value :: i
    end subroutine
  end interface
  procedure(int_printer), pointer :: iprinter
contains
  subroutine work
    implicit none
    integer i
    do i = 1, 2
      call iprinter(i)
    end do
  end subroutine
end module

subroutine sub
  use m
  implicit none
  integer num_prints

  num_prints = 0
  iprinter => myprint
  call work
  print *, 'num_prints=', num_prints
contains
  subroutine myprint(i)
    integer, value :: i
    print *, i
    num_prints = num_prints + 1
  end subroutine
end subroutine

 

use m
implicit none
call sub
! call work  ! error
end

 

In this contrived example, subroutine work uses procedure pointer iprinter to do its printing. Subroutine sub takes advantage of this to count the number of integers printed by work. The program output is:
$ ./a.out
 1
 2
 num_prints= 2
$

 

Note that calling work after sub has completed its execution is invalid. Module variable iprinter is associated with myprint which accesses host variable num_prints.  After sub completes its execution, its stack is freed, including the storage for num_prints.

 

Support for this Fortran 2008 feature is available in XL Fortran, starting with version 14.1.

 

Authors: Rafik Zurob, Yvonne Ma


 

0 comments
0 views

Permalink