Counting an initialised array, and segments

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Jun 26 08:26:31 UTC 2023


On Sunday, June 25, 2023 4:08:19 PM MDT Cecil Ward via Digitalmars-d-learn 
wrote:
> I recently had some problems
>
> dchar[] arr = [ ‘ ‘, TAB, CR, LF … ];
>
> and I got errors from the compiler which led to me having to
> count the elements in the initialiser and declare the array with
> an explicit size. I don’t want the array to be mutable so I later
> added immutable to it, but that didn’t help matters. At one
> point, because the array was quite long, I got the arr[
> n_elements ] number wrong, it was too small and the remainder of
> the array was full of 0xffs (or something), which was good,
> helped me spot the bug.
>
> Is there any way to get the compiler to count the number of
> elements in the initialiser and set the array to that size ? And
> it’s immutable.

Without seeing the errors, I can't really say what the problem was, but most
character literals are going to be char, not dchar, so you may have had
issues related to the type that the compiler was inferring for the array
literal. I don't recall at the moment how exactly the compiler decides the
type of an array literal when it's given values of differing types for the
elements.

Either way, if you want a static array, and you don't want to have to count
the number of elements, then
https://dlang.org/phobos/std_array.html#staticArray should take care of that
problem.

- Jonathan M Davis






More information about the Digitalmars-d-learn mailing list