Array operations, dynamic arrays and length

Alex Parrill via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 1 12:09:34 PDT 2015


On Tuesday, 30 June 2015 at 22:37:34 UTC, ixid wrote:
> 	int[] a = [1,1,1,1];
> 	int[] b = [1,1,1,1];
> 	int[] c;
>
> 	c[] = a[] - b[];
>
> 	c.writeln;
>
> This outputs []. This feels wrong, it feels like something that 
> should have exploded or set the length to 4. If the lengths of 
> a and b are mismatched it throws an exception. It also throws 
> an exception if a dynamic array is longer or a static array is 
> not the same length but is happy when a dynamic array is 
> shorter. Is this intended behaviour and if so why?

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.

Change `int[] c;` to `int[] c = new int[4];` and it works.


More information about the Digitalmars-d-learn mailing list