On Saturday, 11 June 2022 at 01:14:06 UTC, matheus wrote:

So, in the case of "int[] arr = new int[](5)", an array of length 5 of type int will be instantiated and its address will be shared among whoever instantiates "S" and be pointed and accessed through arr.

In the second case, "int[2] arr2", 2 consecutive integer spaces in memory will be allocate independently for each "instantiation" of "S", so different address.

I never saw this before (I mean I never wrote the first case), I'm used to the "int[2] arr2;" way of declaring it, but if I had looked this code without knowing this, I'd be certain that s1.arr and s2.arr would have different addresses.

That's because static arrays are allocated as part of the instance:

```d
struct Foo {
    int[] dyn;
}

struct Bar {
    int[10] stat;
}

assert(Foo.sizeof == 16);
assert(Bar.sizeof == 40);
```


This is a bit weird (At least for a newbie like me), I really think the compiler should emit an warning about this.


At it's core this is just a matter of knowing how two specific language features behave (allocation of static vs. dynamic arrays coupled with member field initialization). If you aren't aware of it and it bites you, then you learn about it and you know it. So would you then really want a warning every time you initialize a static array field?

People getting bit by `new` in field initialization often enough that I think a warning would be helpful. But any such warnings need to be enabled by default to be useful, and must have an off switch for people who don't need them. So the question in each case would be, where's the line between helpful and annoying?

The compiler should be as helpful as it can, but it has to be helpful without getting in the way. There's a significant amount of learning by trial and error in any programming language. So I think there has to be a distinction between things like "easy to do by accident even when you know the deal" and "once you learn it, you're unlikely to do it again".

Reply via email to