Array operations, dynamic arrays and length

J Miller via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 1 17:36:47 PDT 2015


On Wednesday, 1 July 2015 at 21:15:13 UTC, Marc Schütz wrote:
> On Wednesday, 1 July 2015 at 19:09:36 UTC, Alex Parrill wrote:
>> I don't think this is a bug.
>>
>> Since you don't initialize `c` to anything, it defaults to an 
>> empty slice. Array [] operations apply to each element of a 
>> slice, but `c` doesn't have any elements, so it does nothing.
>
> I _do_ think it's a bug. Compare:
>
>     import std.stdio;
>
>     void main() {
>         int[] a = [1,1,1,1];
>         int[] b = [1,1,1,1];
>         int[] c;
>         int[2] d;
>
>         c[] = a[] - b[];  // works
>         c.writeln;        // []
>         d[] = a[] - b[];  // works
>         d.writeln;        // [0, 0]
>         d[] = a[];        // throws!
>         // object.Error@(0): Array lengths don't match for 
> copy: 4 != 2
>     }
>
> So, in the case of subtraction, it assigns only as many 
> elements as the destination has, but for direct assignment, it 
> throws an error. This is clearly inconsistent.

Bug. "c[] = a[] <op> b[]" produces "[]" for operators "-" and 
"/", but "object.Error@(0): Array lengths don't match for vector 
operation: 0 != 4" for operators "+" and "*". Wat.

Oh, and to make things really confusing, "auto e = a[] - b[]" and 
"int[] e = a[] - b[]" both cause "Error: array operation a[] - 
b[] without destination memory not allowed".

Using dmd 2.067.0.


More information about the Digitalmars-d-learn mailing list