From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on polar.synack.me X-Spam-Level: X-Spam-Status: No, score=-0.8 required=5.0 tests=BAYES_00,INVALID_DATE autolearn=no autolearn_force=no version=3.4.4 Path: utzoo!attcan!uunet!know!zaphod.mps.ohio-state.edu!sdd.hp.com!ucsd!ucbvax!IBM.COM!NCOHEN From: NCOHEN@IBM.COM ("Norman H. Cohen") Newsgroups: comp.lang.ada Subject: assigning variant records Message-ID: <9010301603.AA12252@ajpo.sei.cmu.edu> Date: 30 Oct 90 15:20:54 GMT Sender: daemon@ucbvax.BERKELEY.EDU Organization: The Internet List-Id: 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