Power Programming Languages

Power Programming Languages

IBM Power, including the AIX, IBM i, and Linux operating systems, support a wide range of programming languages, catering to both traditional enterprise applications and modern development needs.


#Power

 View Only

BLOCK construct: the add-on to large programs

By Archive User posted Tue October 29, 2013 01:42 AM

  

Originally posted by: Ka_Lin


Author: Ka Lin, Pooja Dayanand

We're trying to summarize the benefit of using the BLOCK construct that is introduced by the Fortran 2008 standard. However, we finally draw a conclusion that the BLOCK construct is useful in very large programs, because in small programs, variables are much easier to keep track of.

Nevertheless, we would like to use the following small programs to illustrate the benefits.

The BLOCK construct improves the readability of code by allowing you to declare variables closer to where they are used in the code. In the following program, BLOCK constructs are used in the SELECT TYPE choices.

program foo
  type circle
    real :: radius
    real :: area
  end type

  type sphere
    real :: radius
    real :: volume
  end type

  interface
    subroutine bar(arg)
      class(*) :: arg
    end subroutine
  end interface

  class(*), allocatable :: obj
 
  allocate(obj, source = circle(3.0, 28.27))

  select type (x => obj)
    type is (circle)        
      block              
        type(circle) :: copy

        copy = x
        call bar(copy)
      end block

    type is (sphere)
      block             
        type(sphere) :: copy

        copy = x       
        call bar(copy)
      end block
  end select
end program foo


The BLOCK construct also prevents you from accidentally overwriting the contents of a variable in case the variable name is reused. See the variable index declared in the BLOCK construct below.

program foo
  integer :: a(4) = [2, 4, 3, 1]
  integer :: index, i

  do i = 1,
    if (a(i) .gt. 3) then
      index = i
    end if
  end do

  block
    integer :: index

    do index = 1, 4
      print *, "a(", index, ") =", a(index)
    end do
  end block

  print *, "index =", index
end program foo

The result is:
 a( 1 ) = 2
 a( 2 ) = 4
 a( 3 ) = 3
 a( 4 ) = 1
 index = 2


#C/C++andFortran
#Fortran-Cafe-for-AIX
0 comments
0 views

Permalink