Why UBound doesnt take into account 0 reporting array size?
Why UBound doesnt take into account 0 reporting array size?
Hi everyone. Mabe someone can solve my confusion about arrays. The initialized array doesn't take into account 0 when reporting UBound(array). Why if I specify Redim array(10) the UBound will report 10, but actually it will have 11 indexes as 0 is accessible too...? Is there any solution to have lets say 5 indexes 0 to 4 and Ubound to be 5? I know I can choose Redim array(1 to 5) then all be correct,UBound will be 5, but what if I want 0 to 4 and still have UBound 5? So is there some workaround for this, or theres nothing to do about it?
-
- Posts: 862
- Joined: May 05, 2015 5:35
- Location: Germany
Re: Why UBound doesnt take into account 0 reporting array size?
UBound notifies the upper bound (the uppermost index) of an array, not the total number of indices. E.g. array(20 to 22) will report a UBound value of 22, although there are only three indices (20, 21 and 22) available.
Re: Why UBound doesnt take into account 0 reporting array size?
Nbr_of_element = Ubound - Lbound + 1
Re: Why UBound doesnt take into account 0 reporting array size?
Code: Select all
dim array1(10) As integer
print "LB=";LBound(array1)
print "UB=";UBound(array1)
dim array2(5 to 10) As integer
print "LB=";LBound(array2)
print "UB=";UBound(array2)
Code: Select all
LB= 0
UB= 10
LB= 5
UB= 10
Re: Why UBound doesnt take into account 0 reporting array size?
Ubound and Lbound are very useful in for...next loops.
In most cases, where Lbound = 0, we can loop "0 to ubound(value)"
Code: Select all
dim as integer value(0 to 3)
for i as integer = lbound(value) to ubound(value)
print i, value(i)
next
Re: Why UBound doesnt take into account 0 reporting array size?
You can write little macros (defines) to do tasks.
For instance flipping between zero based and one based arrays, and a custom ubound.
For instance flipping between zero based and one based arrays, and a custom ubound.
Code: Select all
#define ubnd(a) iif(lbound(a)=0,ubound(a)+1,ubound(a))
#define b0(a) redim preserve a(0 to iif(lbound(a)<>0,ubound(a)-1,ubound(a)))
#define b1(a) redim preserve a(1 to iif(lbound(a)<>1,ubound(a)+1,ubound(a)))
#define show(a) for n as long=lbound(a) to ubound(a):print n,a(n):next
redim as string s(4)
s(0)="zero"
s(1)="one"
s(2)="two"
s(3)="three"
s(4)="four"
show(s)
print "ubound "; ubnd(s)
print
b0(s)
show(s)
print "ubound "; ubnd(s)
print
b1(s)
show(s)
print "ubound "; ubnd(s)
print
b0(s)
show(s)
print "ubound "; ubnd(s)
sleep
Re: Why UBound doesnt take into account 0 reporting array size?
Thanks guys. That's where my confusion was, that UBound doesn't report array size, just upper bound