[Submission] D Slices

Steven Schveighoffer schveiguy at yahoo.com
Tue May 31 11:57:38 PDT 2011


On Tue, 31 May 2011 14:20:20 -0400, eles <eles at eles.com> wrote:

> == Quote from Mafi (mafi at example.org)'s article
>> Am 31.05.2011 18:16, schrieb eles:
>> > Now, why:
>> >
>> > for(iterator from a[0] to a[N-1]){ //etc. }
>> > //let use the above notation for for(i=0; i<=N-1; i++)
>> >
>> > is acceptable, but sudden is no more acceptable to write
>> >
>> > a[for(iterator from 0 to N-1)]
>> >
>> > and one must use
>> >
>> > a[for(iterator from 0 to N]]
>> >
>> > in order to achieve exactly the same?
>> >
>> > The last two expressions are just mental placeholders for a
> [0..N-1]
>> > and for a[0..N] respectively.
>> let
>> for(element from a[0] to a[n])
>> be a notation for
>> for(i=0; i < n; i++)
>> but then, assuming closed intervals, why do I have to write
>> a[i..n-1] to archive the same?
>> You see? This argument of yours is not really good.
>> Mafi
>
> why not write:
>
> for(i=0; i<=n-1; i++)

if n is unsigned int, and 0, then this becomes i = 0; i <= uint.max; i++

Basically, using subtraction in loop conditions is a big no-no.  You are  
much better off to write using addition:

i + 1 <= n

But then i < n looks so much better.

> COnceptually, you are iterating elements from a[0] to a[n-1], this is
> why index goes from 0 to n-1 (even if you write i<n).
>
> What about if length of the array already equals UTYPE_MAX, ie. the
> maximum value representable on the size_t? (I assume that indexes are
> on size_t and they go from 0 to UTYPE_MAX).

First, size_t is the limit of your address space.  You cannot have size_t  
items in any slice.

Second, there are very very few use cases where size_t.max is used as an  
iteration.

-Steve


More information about the Digitalmars-d mailing list