comp.lang.ada
 help / color / mirror / Atom feed
* why can't we declare unconstrained objects ?
@ 2004-12-12 15:43 Michael Mounteney
  2004-12-12 17:39 ` Martin Krischik
                   ` (3 more replies)
  0 siblings, 4 replies; 8+ messages in thread
From: Michael Mounteney @ 2004-12-12 15:43 UTC (permalink / 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;



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

end of thread, other threads:[~2004-12-15 21:47 UTC | newest]

Thread overview: 8+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2004-12-12 15:43 why can't we declare unconstrained objects ? Michael Mounteney
2004-12-12 17:39 ` 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

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