Array bounds with 0-sized array in Fortran

661 Views Asked by At

When allocating zero-sized arrays in Fortran, I am getting counterintuitive behavior.

This code:

program test_zerosized
  implicit none
  integer, allocatable :: a(:),b(:)
  allocate(a(0))
  print *, ' a lower bound = ',lbound(a,1)
  print *, ' a upper bound = ',ubound(a,1)

  allocate(b(0:0))
  print *, ' b lower bound = ',lbound(b,1)
  print *, ' b upper bound = ',ubound(b,1)
  return
end program test_zerosized

Produces the following output:

  a lower bound =            1
  a upper bound =            0
  b lower bound =            0
  b upper bound =            0

Is my compiler (gcc/gfortran 6.2.0) standard conforming? I don't get why lbound(a,1)==1 instead of lbound(a,1)==0, since the total total array size is of zero elements. Thanks!

1

There are 1 best solutions below

2
On

The result you observe is the correct behaviour.

The array a is zero-sized, and lbound works on such arrays (F2008, 13.7.90) (my emphasis):

If ARRAY is a whole array and either ARRAY is an assumed-size array of rank DIM or dimension DIM of ARRAY has nonzero extent, LBOUND (ARRAY, DIM) has a value equal to the lower bound for subscript DIM of ARRAY. Otherwise the result value is 1.

ubound works in a complementary way.

Compare this with the size-1 array b with lower bound zero and upper bound zero.

The allocatable nature of a is not relevant, and you would see the same result with an explicit shape array of zero size.