[Submission] D Slices
eles
eles at eles.com
Tue May 31 13:16:37 PDT 2011
> 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.
Yes, I have been trapped there. More than once. And yes, n=0 is a
special case. An yes, is a big no-no. It also appears when *i* is
unsigned int and you are decrementing it and comparing (with egality)
against 0. The loop is infinite.
For me, conceptually, the problem is simply that unsigned types, once
at zero, should throw exception if they are decremented. It is
illogical to allow such operation. However, type information is only
available at the compile time, so when the program is running is
difficult to take measures against it.
I thought, however, that those exception should be thrown in the
"debug" version.
However, there is no reason to make, instead, UTYPE_MAX a big no-no.
I think a better solution is needed for the following problem:
- avoid decrementing the index outside its logical domain
- maintaining the conceptually-consistent representation of both
index and n as unsigned ints.
Unfortunately, I have no good solution for that problem.
Java dropped completely unsigned types and, thus, they got rid of
this problem. But for me is still a bit illogical to enforce an index
or an array length of being signed, as they are by definition
*always* positive quantities. Is like you are forced to use just half
of the available representable range in order to avoid some corner
case.
You are
> much better off to write using addition:
> i + 1 <= n
> But then i < n looks so much better.
I doubt. It is a matter of taste. I think "looks" does not
necessarily means "good".
> > 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.
That is not the point. "There are very very few cases where array
lengths could not be passed as a second parameter to the function,
beside the pointer to the array". "There are very very few cases when
switch branches should not fall through". "There are very very few
cases when more than 640 kB of RAM would be necessary (so, let's
introduce the A-20 gate (http://en.wikipedia.org/wiki/
A20_line#A20_gate)!!!)" etc.
The point is: why allow an inconsistence?
More information about the Digitalmars-d
mailing list