[comp.lang.c] soliciting ideas on a large struct/union strategy

phil@ux1.cso.uiuc.edu (Phil Howard KA9WGN) (06/10/91)

I am define a data format which consists of a number of different records
or structures.  The first couple of elements in the structure are the same.
The first one identifies the particular type of structure a particular
instance is, and the second identifies the length of the remainder of the
structure, in bytes.

There is going to be a large and growing number of different kinds of
records defined.  What I am looking for suggestions for is way to define
this structure in a header file (or header files) so that it is easy to
maintain.  It would also be nice if the full names of the structures
would as short as possible but giving full meaning.

One possible approach I am considering is a large single struct/union,
looking something like:


struct rec {
	unsigned int type;
	unsigned int length;
	union {
		struct first {
			...
		};
		struct second {
			...
		};
		struct third {
			...
		};
	};
};

The above shows three possible variants of the record type.  The "..."
indicates the elements for each different kind of structure after the
first two.  The sizes and types of the structures will be very different.
However, given a value for "type", only one of the structure definitions
will have the applicable interpretation.  A few might have an identical
structural syntax, but different semantics, but I consider it OK to code
each of them as if they were distinctly different.

I could take other approaches such as simply defining separate structs
for each different structure.  However I don't know how messy that will
end up becoming.

Also, since the first two elements are exactly same for every structure,
I'd like to reference them without a particular reference to any particular
structure itself.
-- 
 /***************************************************************************\
/ Phil Howard -- KA9WGN -- phil@ux1.cso.uiuc.edu   |  Guns don't aim guns at  \
\ Lietuva laisva -- Brivu Latviju -- Eesti vabaks  |  people; CRIMINALS do!!  /
 \***************************************************************************/