Array initialization quiz

Steven Schveighoffer schveiguy at yahoo.com
Wed Nov 30 04:50:29 PST 2011


On Tue, 29 Nov 2011 15:06:11 -0500, Jonathan M Davis <jmdavisProg at gmx.com>  
wrote:

> On Tuesday, November 29, 2011 20:42:59 Marco Leise wrote:
>> Am 29.11.2011, 20:41 Uhr, schrieb Marco Leise <Marco.Leise at gmx.de>:
>> > Am 29.11.2011, 14:53 Uhr, schrieb bearophile  
>> <bearophileHUGS at lycos.com>:
>> >> deadalnix:
>> >>> No it has nothing to do with this bug.
>> >>
>> >> I tend to agree.
>> >>
>> >>> But actually, this exemple should
>> >>> generate a warning at least, or being illegal eventually.
>> >>
>> >> I'd like that code to loop on all array 256 items once, and then stop
>> >>
>> >> :-)
>> >>
>> >> Bye,
>> >> bearophile
>> >
>> > Is it evil if I propose that 'i' should always be size_t and nothing
>> > else?
>>
>> Yes, because you can iterate over -10..10 as well -.-
>
> I would argue that i should always be size_t if it's an index. So,
>
> foreach(i; -10 .. 10) {}
>
> would be valid, but
>
> int[] arr;
> foreach(byte i, val; arr) {}
>
> wouldn't be.

The type of the index should be irrelavent to the underlying loop  
mechanism.

Note that the issue is really that foreach(T i, val; arr) {...} translates  
to for(T i = 0; i < arr.length; ++i) {auto val = arr[i]; ...}

Why can't it be (aside from the limitation in for-loop syntax, but you get  
the idea): for(size_t _i = 0, T i = _i; _i < arr.length; i = ++_i) {auto  
val = arr[_i]; ...}

Same issue with foreach(i; -10..10), what if I wanted to do foreach (ubyte  
i; ubyte.min..ubyte.max + 1).  This should not result in an infinite loop,  
I should be able to use foreach to iterate all the values of ubyte.  The  
compiler should just "figure out" how to do it right.

-Steve


More information about the Digitalmars-d-learn mailing list