Array literals are weird.

user1234 user1234 at 12.de
Wed May 5 08:58:41 UTC 2021


On Saturday, 1 May 2021 at 11:32:47 UTC, Blatnik wrote:
> I love how D redesigned the terrible C/C++ arrays. And it's 
> awesome that array operations like element wise +, -, etc. are 
> built into the language - it makes me want to use arrays and 
> slices for everything. But there are still some rough edges in 
> the design.
>
> What do you expect to happen when you run this:
>
> ```D
> import std;
> void main() {
>   writeln(typeid([1, 2, 3]));
> }
> ```
>
> Maybe I'm crazy, but I would expect `int[3]` to be printed. But 
> `int[]` gets printed instead.
>
> Why? What's the reason for this design?
>
> This automatic downconversion loses potentially useful type 
> information by default. It also means lazy code like this:
>
> ```D
> auto array = [1, 2, 3]; // Type deduced as int[], not int[3]
> ```
>
> performs an allocation, and thus it can't be used in @nogc or 
> -betterC. (Not to mention that it's a completely unnecessary 
> memory allocation).
>
> It also means that functions that take a slice parameter:
>
> ```D
> void foo(int[] bar);
> ```
>
> Can't be called naturally in @nogc or -betterC.
>
> ```D
> foo([1, 2, 3]) // Error: Array literal may cause GC allocation.
> ```

related : https://issues.dlang.org/show_bug.cgi?id=21756

> Instead you have to do this:
>
> ...


More information about the Digitalmars-d mailing list