comp.lang.ada
 help / color / mirror / Atom feed
From: NCOHEN@IBM.COM ("Norman H. Cohen")
Subject: assigning variant records
Date: 30 Oct 90 15:20:54 GMT	[thread overview]
Message-ID: <9010301603.AA12252@ajpo.sei.cmu.edu> (raw)

Kevin Simonson encounters CONSTRAINT_ERROR in the following program:

 >with TEXT_IO;  use TEXT_IO;
 >
 >procedure VACH_PR is
 >
 >   subtype DIGS is integer range 0..9;
 >
 >   type XX (A : DIGS := 0) is record
 >      S : string (1..A);
 >   end record;
 >
 >   type YY is access XX;
 >
 >   X : XX;
 >
 >   Y : YY;
 >
 >   Z : string(1..20);
 >
 >   I : integer;
 >
 >begin
 >
 >   Y := new XX;
 >
 >   loop
 >      put ("String:  ");
 >      get_line (Z, I);
 >      exit when I = 1 and then Z(1) = 'q';
 >      X := (I, Z(1..I));
 >      Y.all := X;
 >      put_line ("Entered string is [" & Y.S & ']');
 >   end loop;
 >
 >end VACH_PR;

When a record with discriminants is created by an allocator, the
allocated object is constrained.  That is, the value of the discriminant
is fixed at the time of allocation.  In particular, the statement
"Y := new XX;" causes Y to point to a record whose discriminant is
fixed to be zero.  (Since there is no initial value in the allocator,
the default discriminant value is used.)  Thus the record value
(0, Z(1 .. 0)) can be assigned to Y.all, but an attempt to assign
(N, Z(1 .. N)) for N/=0 raises Constraint_Error. If

   X := (I, Z(1..I));
   Y.all := X;

is replaced by

   Y := new XX'(I, Z(1 . I));

the Constraint_Error will be avoided, because Y will now point to a
NEW record whose discriminant value is fixed to be the current value of
I.  (On the other hand, if the program runs long enough, the repeated
allocation of new records could lead to Storage_Error.  This can be
avoided by implementing the first garbage-collecting Ada compiler or,
more practically, by calling an instance of Unchecked_Deallocation with
the old value of Y just before the assignment.)

Norman H. Cohen

             reply	other threads:[~1990-10-30 15:20 UTC|newest]

Thread overview: 3+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
1990-10-30 15:20 "Norman H. Cohen" [this message]
  -- strict thread matches above, loose matches on Subject: below --
1990-10-29 23:48 assigning variant records Kevin Simonson
1990-11-19 23:16 ` stt
replies disabled

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