comp.lang.ada
 help / color / mirror / Atom feed
From: gate02@wrandyke.demon.co.uk (Michael Mounteney)
Subject: why can't we declare unconstrained objects ?
Date: 12 Dec 2004 07:43:21 -0800
Date: 2004-12-12T07:43:21-08:00	[thread overview]
Message-ID: <fa59671.0412120743.5cc44da6@posting.google.com> (raw)

Is there a simple way in Ada of simulating C/C++ unions ?  It seems to
me that this is gratuitously prevented, that is, it can be done with
safety, by extending an existing run-time check, but it is in fact
prevented by the compiler.

Hopefully the following commented source will illustrate my point.

with Ada.text_IO;

procedure unconstrained is

	-- Very simple discriminated type
	type thing (what : Boolean) is
		record
			case what is
				when false =>
					letter : character;
				when true =>
					number : natural;
			end case;
		end record;

	-- No problems here:  we provide a discriminant.
	sample : thing := (false, 'X');

	-- This is alright as well of course.
	type thing_pointer is access all thing;

	-- This is also fine:  a pointer to any `thing'.
	indirect : thing_pointer;

	-- This causes a problem:  I want an unconstrained `thing', one
	-- that can be switched between holding a character and a number
	-- but the initialisation makes it constrained.
	sample2 : thing := (true, 12);

	-- Omitting the initialisation doesn't work:
	-- this just fails at compile-time.
	sample3 : thing;

begin
	-- Just reference a field in the `thing'.
	Ada.text_IO.put (sample.letter);

	-- Create a new access object and access its field
	-- This requires a RUN-TIME check that indirect.what is true.
	indirect := new thing (true);
	indirect.number := 12;

	-- This will generate a RUN-TIME failure of course.
	indirect.letter := 'A';

	-- Warning at compile-time, failure at run-time.  I want to change
the
	-- discriminant.  Since the compiler will insert a run-time check
	-- for field selection via an access, why not for a direct variable ?
	sample2 := thing'(false, 'Z');
end;



             reply	other threads:[~2004-12-12 15:43 UTC|newest]

Thread overview: 8+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2004-12-12 15:43 Michael Mounteney [this message]
2004-12-12 17:39 ` why can't we declare unconstrained objects ? Martin Krischik
2004-12-12 17:47 ` Dmitry A. Kazakov
2004-12-12 18:21 ` Martin Dowie
2004-12-12 18:40   ` Jeffrey Carter
2004-12-12 19:24     ` Dmitry A. Kazakov
2004-12-15 13:39 ` David Botton
2004-12-15 21:47   ` Randy Brukardt
replies disabled

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