Array declaration warning

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jun 3 14:05:40 PDT 2015


On 06/03/2015 01:45 PM, Paul wrote:

 > On Wednesday, 3 June 2015 at 20:33:02 UTC, Ali Çehreli wrote:
 >> > pathList[][n] ~= CoOrd(cX, cY);
 >>
 >> I don't think you need the empty [] there. pathList[n] is one of the
 >> paths and you are adding a coordinate to it:
 >
 > Urgh, *that* is how I was confusing myself, the rest of the code 'looks
 > right'. Strange that it compiles without warning and the spurious []
 > have no effect though.

[] means "a slice to all elements". There is no difference in your code 
because pathList is already "a slice to all elements".

Here are a couple of use cases:

1) Being able to traverse a fixed-length array as a range:

import std.stdio;
import std.algorithm;

void main()
{
     int[2] arr = [ 1, 2 ];

     writeln(arr.map!(a => a * 10)); // COMPILATION ERROR
}

The last line cannot be compiled because a fixed-length array cannot 
provide popFront() because its length cannot be changed.

The fix is to slice all elements first by inserting []:

     writeln(arr[].map!(a => a * 10));

There, arr[] is a temporary slice that gets consumed as a range.


2) [] enables array-wise operations:

     int[] arr = [ 1, 2 ];
     arr[] *= 10;    // Multiplies all elements by 10

     arr[] = 42;     // sets all elements to 42


Note the important difference it makes here:

     int[] a = [ 1, 2 ];
     int[] b = [ 3, 4 ];

     a[] = b;    // makes the elements of 'a' same as 'b's elements
     a = b;      // makes 'a' be another slice to 'b's elements

You won't see any difference between the two lines above if you print 
'a', but in the first case a.ptr != b.ptr and in the second case a.ptr 
== b.ptr.

Ali



More information about the Digitalmars-d-learn mailing list