It’s a small thing, but I think it’s worthwhile to mention it:
Description
When initializing an array, the length should be specified (not sure why, as it could be acquired from the number of items of the initialization). However, if this value is lower than the amount of items to be initialized, compilation succeeds.
Example 1
Numbers : int[1] = [ 1, 2, 3]
Example 2
(found the problem with the code below, but example 1 shows the minimal example)**
Early versions of GPScript did not have variably sizable arrays
Similarly, early versions of GPScript didn’t support initialization as part of declaration
Requiring the explicit length gives you a built-in test if you are using a FOR loop to initialize the array and/or you assign items manually and something is added unexpectedly.
Not 100% sure if I understand this. Do you mean the number in the square brackets String[1] does not matter? Since 1 clearly is not enough to fit 3 elements inside, still giving no error… Hope it cannot result in a memory corruption error, or in case if the number is ‘too high’, will it cost more unneeded memory?
It’s a little more subtle than that and again this is somewhat legacy as array implementation has changed significantly in more recent versions of GP
Consider the following scenarios
var
Numbers: Integer [1]
initialization
Print(Size(Numbers))
end
// Displays 1
var
Numbers: Integer [1]
initialization
Print(Numbers[1]) // I.e, the second element
end
// This will generate a run-time array index out of
// bounds error as there is only one element
var
Numbers: Integer [1] = [3, 4, 5, 6]
initialization
Print(Size(Numbers))
end
// Displays 4
In other words, in example 3, the declared array size is basically ignored and the size is defined by the number of elements in the initializer
FYI This will generate a warning message in the next release. I would have made it an error but that would cause this mistake to be a breaking change for existing gig files
Technically, all arrays have the same underlying size, 256 values
However, arrays know how many items are actually contained in them.
I see now the issue with legacy not wanting to break it. And it’s good to show a warning in the next release.
For me, it’s good to know I don’t have to care about the initialization number inside the array declaration. Meaning that example 3 I’m glad it shows 4.