C union problems (or is a pointer a pointer?)
Henry Spencer
henry at utzoo.uucp
Thu Apr 27 07:59:03 AEST 1989
In article <15058 at sequent.UUCP> bills at sequent.UUCP (Bill Sears) writes:
>The problem with this is that in order to declare a union, you must
>introduce a new variable into the structure (i.e. dummy). Now my two
>pointers must be accessed as "a.dummy.menu" and "a.dummy.action",
>rather than (the preferable) "a.menu" and "a.action". One way to
>solve this is not to use a union.
Another way is to use the union but use #defines to hide the extra
name:
union {
MENU *dumenu;
ACTION *duaction;
} dummy;
#define menu dummy.dumenu
#define action dummy.duaction
so you can say "a.menu" and have it work. It's a bit inelegant, but it
works very nicely.
> char *objptr; /* or int * or long * */
>
>Now, by casting objptr to be the type of pointer that I am using
>at any given time, I can get rid of any compile errors, but is this
>always guaranteed to work? In other words, is a pointer a pointer?
No; in the general case a cast from one type of pointer to another yields
machine-dependent and unpredictable results. However, "void *" and (as a
grandfather clause) "char *" are exceptions: they are guaranteed to be
able to hold any pointer, and conversions to and from them are guaranteed
safe.
>Although this is probably a matter of personal taste and programming
>style, which of the above implementations is the "most desirable"?
I would give the nod to union-plus-#define, which avoids waste of storage
and, at the cost of slight inelegance at the declaration, avoids notational
clumsiness at the points of use.
>Was the Pascal variant record syntax designed to overcome the above
>restrictions with the C union, or is it just coincidental that it does?
They're somewhat differently-flavored solutions to the same problem.
Pascal wins on this particular point of syntax-at-point-of-use, at the
cost of more complex structure-declaration syntax.
--
Mars in 1980s: USSR, 2 tries, | Henry Spencer at U of Toronto Zoology
2 failures; USA, 0 tries. | uunet!attcan!utzoo!henry henry at zoo.toronto.edu
More information about the Comp.lang.c
mailing list