Using "[]" for empty array (instead of null)

Chris Sauls ibisbasenji at gmail.com
Wed Mar 1 12:55:02 PST 2006


Jari-Matti Mäkelä wrote:
> It should be someday also possible to create dynamic arrays of a given
> length without this much clutter:
> 
>  type[] array;
>  array.length = x;

Currently:
# type[] array = new type[x];

> 
> Multidimensional arrays are a bit difficult too:
> 
>  type[][] array;
>  array.length = y;
>  foreach(inout type[] row; array) row.length = x;

Currently:
# type[][] array = new type[y][];
# foreach (inout row; array) row = new type[x];

I would love to see the ability to do:
# type[][] array = new type[y][x];

As to the subject of array literals, I've always been fond of this syntax:
# int[] foo = new int[] [1, 2, 3];

However, it does suffer a couple of problems.  For one, because it uses []'s instead of 
{}'s or ()'s, it makes for a parsing trap.  In most cases, this is escapable because we 
already know the type we are expecting (from the decleration before the initializer) so we 
can just count bracket pairs, but what if we want to use 'auto'?

# auto foo = new int[] [1, 2, 3];

In this case, assuming D gets static matrices in the future (which would be nice), this 
would probably assign to foo an array of three dimensional matrices of volume 1x2x3.  Not 
quite what we wanted!!

I would say go back to using {}'s, and perhaps prepend struct initializers with a 'new' 
instruction as well.  Of course, if we get this 'local' instruction for stack allocating, 
then one could opt to use that instead.

# auto foo = new int[] {1, 2, 3};
# auto bar = local MyStruct {"tag"c, some_flags, foo};

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list