array setting : Whats going in here?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Oct 9 02:19:20 UTC 2023


On Sunday, October 8, 2023 8:08:46 AM MDT Imperatorn via Digitalmars-d-learn 
wrote:
> On Saturday, 7 October 2023 at 00:00:48 UTC, claptrap wrote:
> > char[] foo;
> > foo.length = 4;
> > foo[] = 'a'; // ok sets all elements
> > foo[] = "a"; // range error at runtime?
> > foo[] = "ab"; // range error at runtime?
> >
> > So I meant to init with a char literal but accidently used
> > double quotes. Should that even compile? Shouldn't the compiler
> > at least complain when trying to init with "ab"?
>
> Even though you now have gotten answers, I still agree with you
> that there should be some kind of "warning" or suggestion like,
> did you mean to assign incompatible types?
>
> It could just check the element type and see if it matches the
> rhs type.

Except that in those examples, they _do_ match. It's perfectly valid to copy
elements of a string to a char[]. It's just copying immutable(char) to char.
The compiler would complain if it couldn't implicitly convert the element
type in the array being assigned from to the element type in the array being
assigned to. The problem here is simply that the lengths of the arrays don't
match.

And in general, the compiler has no way of knowing whether the lengths
match, because the lengths are dynamic. In this particular case, it could
figure it out if it did sufficient flow analysis, but that's the sort of
thing that typically isn't done in D, because it gets to be expensive and
tends to result in inconsistent behavior, because small changes to the code
could drastically change what the compiler is able to figure out.

If the lengths were static, then the compiler actually would complain. e.g.

    foo[0 .. 3] = bar[1 .. 2];

would result in a compilation error such as

q.d(5): Error: mismatched array lengths 3 and 1 for assignment
        `foo[0..3] = bar[1..2]`

So, the compiler will complain both if it can't implicitly convert the
element types to make the assignment work and if it can statically see that
the lengths of the arrays don't much.

As such, I'm not sure that there's actually anything that the compiler could
do here to catch the problem in the OP's case (at least not without doing
code flow analysis, which isn't going to happen).

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list