Array literals are weird.

Mike Parker aldacron at gmail.com
Sat May 1 15:14:49 UTC 2021


On Saturday, 1 May 2021 at 12:27:30 UTC, Blatnik wrote:

> I still see no reason `[1, 2, 3]` should ever _not_ be 
> considered a `int[3]`, unless you explicitly ask for it:

I strongly disagree. That array literals produce dynamic arrays 
made sense to me from the day I found D, and it still makes sense 
18 years later.

If they were to produce static arrays, then what happens here?

```d
int[] a = [1, 2, 3];
return a;
```

In order for this to work as expected, then this particular 
literal would have to be allocated on the GC heap, which is then 
inconsistent with the normal behavior. Right now, the compiler is 
free to elide allocations for literals when it can, but that's 
not an optimization, not an inconsistency.

And what about this?

```d
doSomeMatrixStuff3x3(
     [1.0, 0.0, 0.0,
      0.0, 1.0, 0.0,
      0.0, 0.0, 1.0]
);
```

Now I'm passing 9 floats by value unless I remember to do 
whatever needs to be done to indicate that this should be dynamic 
(`.dup`).

Static array literals just seem backwards to me. With dynamic 
array literals, I don't have to think about it.

Moreover, I really would hate to see either `@nogc` or BetterC 
have any impact on language changes. Those are the *exceptional* 
cases. D is a GC'ed language. `@nogc` and BetterC are more 
restricted subsets.


More information about the Digitalmars-d mailing list