Beliavsky / FortranTip

Short instructional Fortran codes associated with Twitter @FortranTip
https://zmoon.github.io/FortranTipBrowser/
The Unlicense
64 stars 14 forks source link

Tip: named if block #29

Open Beliavsky opened 2 years ago

Beliavsky commented 2 years ago

An if block can be named, for example

name: if (x > 0) then
   print*,"+"
else
   print*,"-"
end if name

One use besides documentation is to skip code outside of an inner if block when if blocks are nested, by exiting the outer if block.

program named_if_block
implicit none
real :: x
integer :: i
do i=1,10
   call random_number(x)
   test_big: if (x > 0.5) then
      if (x > 0.9) then
         print*,x," is very big"
      else if (x > 0.8) then
         print*,x," is quite big"
      else
         print*,x," is big"
         exit test_big
      end if
      print*,"x**2=",x**2 ! execute if x > 0.8
   else
      print*,x," is small"
   end if test_big
end do
end program named_if_block

Sample output:

  0.567683935      is big
  0.790556431      is big
  0.631362140      is big
  0.144122779      is small
   4.83593345E-02  is small
  0.504784107      is big
  0.842326403      is quite big
 x**2=  0.709513783    
  0.790282488      is big
  0.906665266      is very big
 x**2=  0.822041929    
  0.454891980      is small