negative lengths and reverse pointers

Bill Baxter dnewsgroup at billbaxter.com
Thu Oct 19 19:14:21 PDT 2006


Jarrett Billingsley wrote:
> "Ameer Armaly" <ameer_armaly at hotmail.com> wrote in message 
> news:eh8mkk$728$1 at digitaldaemon.com...
>> Hi all.  After thinking about foreach_reverse and arrays, a rather strange 
>> idea hit me: what if we had reverse arrays, where whenever you tried to 
>> access an element it would go backwards instead of forwards in a memmory 
>> block to find it?  This could be indicated by a negative length; if length 
>> is negative, the pointer points to the end of the memmory chunk as opposed 
>> to the beginning.  When you assign a negative length, all the compiler 
>> would have to do is find the endpoint of the positive version of the 
>> length you gave it and set the pointer to point to that.  This way 
>> array.reverse simply = array.length * -1, which would allow you to go 
>> through an array backwards with much more efficiency.  Kind of random, but 
>> might be useful; ideas?
> 
> I really like the idea, though I'm not sure what kind of overhead it'd add 
> to the implementation.. even in release mode, it'd have to figure out 
> whether to index forwards or backwards based on the length of the array. 
> Maybe someone could knock up a simple templated test case to see how it 
> performs? 
> 
> 

It's a cute idea.  But I fear it will cause pain outside the context you 
describe.  Take the classic:

   for(int i=0; i<array.length; i++)
   {
       ...array[i]...
   }

Ouch, probably not the behavior I intended if someone passes me a 
negative length array.  So maybe you make length always return a 
positive number?  But then you've still lost pointer equivalence, so 
array[0] != (&array[0])[0].  Ok, so maybe you make the 
&-of-array-element operation smarter too, so that it knows that 
&array[0] should return the address of the last element.  But you've 
still lost equivalence of array[1] and (&array[0])[1] Etc.  Seems like 
you need to follow this through very carefully to find out all the 
ramifications.  In the end I think the loss of interchangeability with a 
pointer is going to be an issue.

--bb



More information about the Digitalmars-d mailing list