comp.lang.ada
 help / color / mirror / Atom feed
From: Adam Beneschan <adam@irvine.com>
Subject: Re: Normalizing array indices
Date: Fri, 28 Oct 2011 13:36:19 -0700 (PDT)
Date: 2011-10-28T13:36:19-07:00	[thread overview]
Message-ID: <f40f13f7-0ed4-4026-9c37-4040260411f9@u24g2000pru.googlegroups.com> (raw)
In-Reply-To: Pine.LNX.4.64.1110282013540.21821@medsec1.medien.uni-weimar.de

On Oct 28, 11:58 am, Stefan.Lu...@uni-weimar.de wrote:
> Hi all, does anyone know a way to change the array indices of a subprogram
> parameter to start with a default index? This question occurred to me when
> I happened to discover a subtle bug in a sort procedure I had implemented.
>
>   generic
>     type Element_Type is private;
>     type Sort_Array_Type is array (Positive range <>) of Element_Type;
>     with function "<" (Left, Right: Element_Type) return Boolean is <>;
>   procedure Sort(A: in out Sort_Array_Type);
>
> I had a reasonable amount of black box tests and Sort passed all of them.
>
> Some time later, I added a test with A'range being  
>    Positive'Last -2 .. Positive'Last
> and boooom -- got a Constraint_Error. As it turned out, there was a
> Positive index variable which could take the value A'Last+1 -- which is
> perfectly OK except when A'Last = Positive'Last. To rescue my
> implementation I considered something like
>
>   procedure Sort(A: in out Sort_Array_Type) is
>     Alias_A: Sort_Array_Type(1 .. A'Length) renames A;
>   begin
>     ... -- apply your favorite sorting algorithm to Alias_A;
>   end Sort;
>
> but the compiler didn't like that renaming:
>   "constraint not allowed in object renaming declaration".

procedure Sort (A : in out Sort_Array_Type) is
  subtype A_Type is Sort_Array_Type (1 .. A'Length);
  Alias_A : A_Type renames A_Type(A);
begin
  ...
end Sort;

The type conversion is necessary in order to get the indexes to
"slide".  If you do this:

  Alias_A : A_Type renames A;

the compiler will accept it, but you're likely to get
Constraint_Errors at runtime.

                        -- Adam



  reply	other threads:[~2011-10-28 20:39 UTC|newest]

Thread overview: 17+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2011-10-28 18:58 Normalizing array indices Stefan.Lucks
2011-10-28 20:36 ` Adam Beneschan [this message]
2011-11-01 20:18   ` Stefan.Lucks
2011-10-28 21:13 ` Randy Brukardt
2011-10-29  7:29   ` Pascal Obry
2011-10-29 19:18     ` Jeffrey Carter
2011-10-29 19:58       ` tmoran
2011-10-29 21:15         ` Simon Wright
2011-10-29 20:41       ` Randy Brukardt
2011-11-01 20:49         ` stefan-lucks
2011-11-01 20:44     ` stefan-lucks
2011-11-01 20:43   ` stefan-lucks
2011-11-02 12:16     ` Robert A Duff
2011-10-29  9:05 ` Simon Wright
2011-10-29  9:23   ` Dmitry A. Kazakov
2011-11-01 20:55   ` stefan-lucks
2011-11-02 12:14   ` Robert A Duff
replies disabled

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox