comp.lang.ada
 help / color / mirror / Atom feed
* Correct use of variants
@ 2005-11-07 10:32 Maciej Sobczak
  2005-11-07 12:52 ` Jean-Pierre Rosen
                   ` (2 more replies)
  0 siblings, 3 replies; 5+ messages in thread
From: Maciej Sobczak @ 2005-11-07 10:32 UTC (permalink / raw)


Hi,

Consider this:

with Ada.Text_IO;
with Ada.Integer_Text_IO;
use Ada.Text_IO;
use Ada.Integer_Text_IO;

procedure Hello is

    type Chooser is (First, Second);

    type Discriminated(Which : Chooser) is
       record
          case Which is
             when First =>
                X : Integer;
             when Second =>
                Y : Integer;
          end case;
       end record;

    A : Discriminated := (Which => First, X => 7);

begin

    Put(A.X);   -- prints 7
    New_Line;

--   does not compile:
--   A := (Which => Second, Y => 5);
--
--   Put(A.Y);   -- should print 5
--   New_Line;

end Hello;


Above, A is declared as a value of *constrained* type (what's the formal 
name for this - "anonymous constrained subtype"?), with the discriminant 
Which fixed to value First. Later the variant cannot be changed as shown 
in that the commented part would not compile.

What is the correct way to achieve the declaration of A with the 
possibility of changing the discriminant later? One of the ways is to 
use *some* default value for the discriminant, but I might have 
difficulty deciding which value is better than the others for this role. 
An arbitrary choice would create a misleading message to the reader that 
the particular value is considered to be "best" or "idle" or "starting" 
or whatever. In addition, having a default value for the discriminant 
means that it's not obligatory to initialize the variable A while it's 
declared and I would like to keep this enforced.


--
Maciej Sobczak : http://www.msobczak.com/
Programming    : http://www.msobczak.com/prog/



^ permalink raw reply	[flat|nested] 5+ messages in thread

end of thread, other threads:[~2005-11-08  8:40 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2005-11-07 10:32 Correct use of variants Maciej Sobczak
2005-11-07 12:52 ` Jean-Pierre Rosen
2005-11-07 19:46 ` Jeffrey R. Carter
2005-11-07 23:40 ` Stephen Leake
2005-11-08  8:40   ` Maciej Sobczak

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