Monday, December 11, 2006

dynamic arrays and array sizes

Arrays are supported for some time, but dynamically creating an array wasn't possible yet. Time to change that. The syntax is simple:
procedure xxxx(a & b : nat)
var x : * [5] int = new [5] int()
var y : * [][] real = new [a][b] real
end
As you can see, the syntax is "new" followed by the type of the array and an optional empty pair of parentheses. Dynamic arrays initialize there elements with their default value. The size of the new array must be fully specified (but for its elements this is not required):
 new [] int      # illegal
new [][10] int # illegal
new [10] * [] int # allowed
This brings us to the compatibility of array sizes. When pointing an array variable to an array, the sizes that ARE specified must be evaluatable at compile time and be equal. But you don't HAVE to specify the sizes of course. Open arrays accept any size, this means no size specified or a size that isn't known at compile time.
const globalC : nat = 17  # constant field

procedure test(i : * [] int, j : * [17] int, n : nat)
var a : * [9] int = j # ERROR: 9 != 17
var b : * [17] int = j # OK
var c : * [17] int = i # ERROR: unknown size of i
var d : * [globalC] int = j # OK, globalC = 17
var e : * [n] = j # ERROR : value of n unknown
var f : * [] int = i # OK
var g : * [] int = j # OK
end
For now you cannot specify an initializer for an array. That's why you don't specify arguments between the parentheses when creating a dynamic array. And that's why an array variable or field can't have an initializer part.

No comments: