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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With