making it easier to use unions

Chris Torek chris at umcp-cs.UUCP
Mon Jun 30 14:02:07 AEST 1986


In article <1725 at brl-smoke.ARPA> rgenter at BBN-LABS-B.arpa (Rick Genter)
points out that unions often contain `useless' structures and
ad hoc `constructed' names, followed by a series of `#define's:

>	#define	dr_word1	_dr_u1._dr_word1
>	#define	dr_bit1		_dr_u1._dr_w1._dr_bit1
>	#define	dr_value	_dr_u1._dr_w1._dr_value
>
>usually bracketed by a comment saying something about "making it easier to
>access the bit fields."

This is true, and I, at least, have found this particular kludge
annoying, yet useful.  Rick suggests an extension to avoid the
constructed names, removing much of the kludgery.

His suggested method for doing this seems to me, however, rather
confusing; he suggests simply omitting the labels:

>	struct	device	{
>		union	{
>			unsigned short	dr_word1;
>			struct	{
>				unsigned dr_bit1  : 1;
>				unsigned dr_bit2  : 1;
>				unsigned dr_value : 3;
>				unsigned	   : 2;
>				unsigned dr_ctrl  : 1;
>				unsigned dr_val2  : 8;
>			};	/* <= note there is no label here */
>		};		/* <= nor here */
>
>		unsigned short	dr_data;
>
>		union	{
>			< another control word >
>		};		/* <= nor here */
>	};

The problem here is that constructs such as

	struct { int x; char *y; };

and

	union { short a; char b[2]; };

are already legal, if useless, and this particular extension would
have to be implemented with a rule such as `if a struct or union
has no tag name and declares no data objects, the fields it declares
migrate (along with their offset values) into the containing struct
or union'.  I am not certain why, but this `feels' confusing to me.

If this were to be implemented, I would like to see some sort of
keyword indicating that the `dummy' structures or unions are there
to declare fields in the next outer level:

	struct drdevice {
		this_is_a_fake union {
			u_short	dr_word1;
			this_is_a_fake struct {
				u_int	dr_bits1:1,
					dr_bits2:15;
			};
			/* dr_bits1 and dr_bits2 are now available in
			   the union */
		};
		/* dr_word1, dr_bits1, and dr_bits2 are now all
		   available in struct drdevice */
		u_short	dr_word2;
		...
	};

or similar.  *This*, unfortunately, requires yet another keyword
(`this_is_a_fake' is not a serious suggestion).  (I suppose one
could appropriate `entry', but that name is terrible.  `void'
perhaps, but that one is already way overused in the draft standard.)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 1516)
UUCP:	seismo!umcp-cs!chris
CSNet:	chris at umcp-cs		ARPA:	chris at mimsy.umd.edu



More information about the Comp.lang.c mailing list