1) For testing if the array is sized:
The safer syntax is to not use any array index but rather:
If ubound(array) >= lbound(array) then '' verified only if array is sized
2) For clearing the array:
Your syntax uses the New (placement) operator which allows to construct object(s) (no allocate memory) at an existing memory location:
New(address) datatype[ count ]
where:
address = @array(lbound(array))
address of the first element of array
datatype = typeOf(array)
datatype of array (Integer)
count = ubound(array) - lbound(array) + 1
number of elements of the array
Constructing Integers at existing memory location consists only to clear the corresponding memory.
The New (placement) instruction returns then a typed pointer to the first constructed memory address which is the address of the first array element.
As optimization, one can use the dereferenced version of New (placement):
*New(address) datatype[ count ]
which always constructs the Integers and then which returns the value of the first constructed element (0 in this case).
This can allow not to construct the last element of the array but to assign it to the value of the first array element (0 after construction), instead of an useless assignment like your solution (in addition, that suppresses adding
'+1' in the expression of number of elements).
3) Example of safe and optimized code (for 1-dimension array and number of array elements > 1):
Code: Select all
Dim As Integer array(10)
For I As Integer = 0 to 10
array(I) = (I+1) * 10
Next I
For I As Integer = 0 to 10
Print array(I)
Next I
Print
If Ubound(array) > Lbound(array) Then
array(Ubound(array)) = *New (@array(Lbound(array))) Typeof(array)[Ubound(array) - Lbound(array)]
'' last array element not constructed but only assigned (to 0 = value of first element after construction)
Elseif Ubound(array) = Lbound(array) Then
array(Lbound(array)) = 0
End If
For I As Integer = 0 to 10
Print array(I)
Next I
Sleep
4) Clearing N-dimension array (with N>1):
The full optimization as above is not useful because it would add a subtracting
'-1' in the expression of the number of elements.
Your code is correct if
'array(0, 0)' is a valid array element, otherwise use for example
'array(lBound(array), lBound(array, 2)) = *New .....'.
5) Final remark:
For clearing a numeric array, 'Clear' appears to be a little faster than 'New (placement)'.