fortran66のブログ

fortran について書きます。

Fortran 2018 の import none で internal procedure も安心!

内部手続きも import none で implicit none 的に


intel fortan v.19 のマニュアルを眺めていますと、fortran 2018
の新機能として、import 命令の拡張がありました。

software.intel.com

その中で特に目を引いたのは、internal procedure での import による変数スコープの制御です。従来、無条件に共有変数として見えていたものを、適宜従来のまま共有したり、共有せず未定義にしたり、スコープを制御できるようになっています。

これは特に main program 中の internal procedure に対して裨益するところ大な機能です。

main program では、普通にループ変数など捨て変数を宣言しますが、これが internal procedure にも共有されてしまうため、ついうっかり local に宣言せずにループ変数などを使ってしまい、思わぬバグを引き起こしてしまうことがあります。そのためか fortran 90 時代から、main program では internal procedure を使うなと言われることがままありました。

import, none を使うことにより、丁度 implicit none をしたときのように、main program で宣言した変数は、共有されず見えなくなります。これにより、不用な過ちを避けることが出来るようになります。これは中々に気の利いた改良だと思います。

ソースプログラム

以下では、変数 j のみを共有させています。

    program f2018
      implicit none
      integer :: i, j
      do i = 1, 10
        j = i  
        print *, func(i), j
      end do
      stop
    contains
      integer function func(i) result(ires)
  !     import, none
        import, only : j
        implicit none ! no effect
        integer, intent(in) :: i
        ires = 0
        do j = 1, i**2 - 1
          ires = ires + i
        end do
      end function func  
    end program f2018

実行結果

           0           1
           6           4
          24           9
          60          16
         120          25
         210          36
         336          49
         504          64
         720          81
         990         100
続行するには何かキーを押してください . . .

Modern Fortran Explained (Numerical Mathematics and Scientific Computation)

Modern Fortran Explained (Numerical Mathematics and Scientific Computation)

  • 作者: Michael Metcalf,John Reid,Malcolm Cohen
  • 出版社/メーカー: Oxford University Press, U.S.A.
  • 発売日: 2011/05/08
  • メディア: ペーパーバック
  • この商品を含むブログを見る
Numerical Computing with Modern Fortran (Applied Mathematics)

Numerical Computing with Modern Fortran (Applied Mathematics)

Introduction to Modern Fortran for the Earth System Sciences (Springerbriefs in Earth System Sciences)

Introduction to Modern Fortran for the Earth System Sciences (Springerbriefs in Earth System Sciences)

Introduction to Programming with Fortran: With Coverage of Fortran 90, 95, 2003, 2008 and 77

Introduction to Programming with Fortran: With Coverage of Fortran 90, 95, 2003, 2008 and 77