4

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
  • 3
    Well if Lbound( a ) = 0 and Ubound( a ) = 0 it's not zero sized, there's 1 element, namely a( 0 ) Commented Nov 20, 2018 at 13:50

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

got it, thanks @francescalus, so in some sense the standard wants bound-based size checking to be consistent: for array a, size(a) == ubound(a)-lbound(a)+1 == 0-1+1 == 0, while for array b, size(b) == ubound(b)-lbound(b)+1 == 0-0+1 == 1, which contains 1 element as @Ian Bush pointed out
Indeed (taking care to consider the extents/bounds/sizes in terms of individual ranks).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.