C union problems (or is a pointer a pointer?)

Doug Gwyn gwyn at smoke.BRL.MIL
Wed Apr 26 16:58:01 AEST 1989


In article <15058 at sequent.UUCP> bills at sequent.UUCP (Bill Sears) writes:
>Now my two pointers must be accessed as "a.dummy.menu" and "a.dummy.action",
>rather than (the preferable) "a.menu" and "a.action".

If that really, really bothers you, first consider using "u" instead of
"dummy" for the union identifier. and if that's still not enough then
try something like

struct {
	char	desc[40];
	objtype	stype;
	union {
		MENU	*umenu;
#define menu u.umenu
		ACTION	*uaction;
#define action u.uaction
	} u;
} a;

Then you can type your beloved "a.action" etc.
Personally I don't think typing the extra "u." is such a big deal.

>In other words, is a pointer a pointer?

No, different pointer types in general have different requirements
(although all pointers to structures have to have similar representation,
by a fairly subtle chain of reasoning).  There is a generic pointer
type (void* in ANSI C), but it's a mistake to use it unnecessarily,
because you lose type checking that way.  (There can also be run-time
overhead for pointer conversions in some implementations.)

>Was the Pascal variant record syntax designed to overcome the above
>restrictions with the C union, or is it just coincidental that it does?

There is no evidence I know of that Wirth was aware of C when he designed
Pascal.  (I'm not sure whether or not it was even chronologically possible.)
Pascal variant records and C unions don't address quite the same need,
although there are some similarities.  I'm actually quite glad that C
unions don't require an associated variant-selector tag; there are times
when it would get in the way.

Early versions of C allowed structure members to be accessed with
pointers to other structure types, which would have provided you with
an alternative solution to your "problem".  Each structure type was
given its own member name space somewhere around 1977, as I recall.
I think most experienced C programmers would agree with the change.
(Not that we have any choice in the matter.)



More information about the Comp.lang.c mailing list