why static array can be reassigned with new allocation?

rassoc rassoc at posteo.de
Sat Oct 15 19:58:12 UTC 2022


On 10/15/22 20:56, mw via Digitalmars-d wrote:
> Of course, with these different syntax, the compiler can do more for static checking:
> 
> ```
>    int[3] a;            // compiler know it's a static array
>    a = b;               // compiler issue error: static array cannot be re-assigned
>    a = new int[5];      // compiler issue error: static array cannot be re-assigned
>    a = what_ever_here;  // compiler issue error: static array cannot be re-assigned
> 
>    a[] = b[];    // content assignment ok; but if b's size can be known statically at compile time and is different from 3, issue error at compile time; otherwise run time error.
> 
>    a[start_a .. end_b] = b[start_b .. end_b];  // same as above, content assignment
> ``` 

Static array doesn't mean they can't be mutable; they are simply stack allocated and value types.

Also, that checking will be done when it's only static arrays:

import std;
void main() {
     int[3] a;
     int[5] b;
     a = b;     // Error: mismatched array lengths, 3 and 5
     a[] = b[]; // Error: mismatched array lengths, 3 and 5
     a[10] = 0; // Error: array index 10 is out of bounds `a[0 .. 3]`
}

D, as of right now, doesn't do these compile-time checks when dynamic arrays are involved even if it could, which isn't optimal, I agree.

> This current syntax in D is as clear as mud.

Maybe these links help:

Cloning: https://forum.dlang.org/post/mailman.3.1473548067.2994.digitalmars-d-learn@puremagic.com
Array types and ops: https://dlang.org/spec/arrays.html


More information about the Digitalmars-d mailing list