Static arrays, typeof and IFTI?

bearophile bearophileHUGS at lycos.com
Tue Oct 11 15:09:02 PDT 2011


Don Wrote:

> On 11.10.2011 18:54, bearophile wrote:
> > Andrei Alexandrescu:
> >
> >> I was more enthused about that, but later I realized there are very few
> >> situations in which one reasonably has a fixed-size array that is large
> >> enough to make counting inadequate and is also updated often enough to
> >> make the feature worthwhile. It's one of those features that are nice to
> >> have but are not really missed in real code.
> >
> > I am not going to appreciate a language/compiler that accepts and compiles this program silently. This trap has caused a bug in my code time ago:
> >
> > int[3] a = [1, 2];
> > void main() {}
> 
> I've hit that bug many, many times. But...
> 
> > The usage of [$] in that case avoids that kind of bug...
> 
> How? The code above would still compile.

What is the "correct" version of the code? The array [1,2] of length 2 or a sequence literal [1,2,x] (with x = some not yet specified) with length 3? The compiler can't know what the right code is.
If you write [$] on the left you are saying to the compiler that the correct thing is the sequence literal you have written on the right of the equal sign.
If you don't use [$] it means you want exactly N items (so if the sequence literal on the right contains less than N then there is a bug).
And finally some people have even said that if you put a [, ...] at the end of the sequence literal on the right of the equal sign then the specified N number of items on the left is the correct information, and the not specified items in the sequence literal on the right need to be filled with .init.


> Would be much better to just 
> ban assigning an array literal to an static array of different length.

For me this is an acceptable solution, it's safe, and it's the simplest one. This was present in the the patch in Bugzilla (but because of my silly poking nose it was later removed). But it sometimes forces you to count items manually (and in some very uncommon cases forces you to add leading zeros manually, but this is not a problem).

Bye,
bearophile


More information about the Digitalmars-d mailing list