Beliavsky / FortranTip

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

Tip: bounds of assumed shape arrays #43

Open Beliavsky opened 2 years ago

Beliavsky commented 2 years ago

The lower bounds of an assumed shape dummy argument are 1 or the lower bounds specified in the procedure declaration, regardless of the lower bounds of actual argument in the caller. Lower bounds of a derived type array component are preserved.

module bounds_mod
implicit none
type :: vec
   real :: x(0:2)
end type vec
character (len=*), parameter :: fmt = "(a30,*(1x,i4))"
contains
subroutine print_bounds(x)
real, intent(in) :: x(:)
print fmt,"in print_bounds, bounds =",lbound(x),ubound(x)
end subroutine print_bounds
!
subroutine print_bounds_0(x)
real, intent(in) :: x(0:)
print fmt,"in print_bounds_0, bounds =",lbound(x),ubound(x)
end subroutine print_bounds_0
!
subroutine print_bounds_mat_3_5(x)
real, intent(in) :: x(3:,5:)
print fmt,"in print_bounds_0, bounds =",lbound(x),ubound(x)
end subroutine print_bounds_mat_3_5
!
subroutine print_bounds_vec(v)
type(vec), intent(in) :: v
print fmt,"in print_bounds_vec, v%x bounds =",lbound(v%x),ubound(v%x)
end subroutine print_bounds_vec
end module bounds_mod
!
program main
use bounds_mod
implicit none
real :: x(0:3),xmat(-1:5,2:4)
type(vec) :: v
print fmt,"in main, bounds =",lbound(x),ubound(x)
call print_bounds(x)
call print_bounds_0(x)
print fmt,"in main, bounds =",lbound(xmat),ubound(xmat)
call print_bounds_mat_3_5(xmat)
print fmt,"in main, v%x bounds =",lbound(v%x),ubound(v%x)
call print_bounds_vec(v)
print "(/,a)","calling print_bounds with v%x"
call print_bounds(v%x)
end program main
! output:
!              in main, bounds =    0    3
!      in print_bounds, bounds =    1    4
!    in print_bounds_0, bounds =    0    3
!              in main, bounds =   -1    2    5    4
!    in print_bounds_0, bounds =    3    5    9    7
!          in main, v%x bounds =    0    2
! in print_bounds_vec, v%x bound    0    2
! 
! calling print_bounds with v%x
!      in print_bounds, bounds =    1    3