Re: [vox] [OT] unions
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [vox] [OT] unions
On Fri, Aug 24, 2001 at 04:05:22PM -0700, Joel Baumert wrote:
> I think that unions had a purpose in the past, but government
> regulation has made them less and less useful. Normal everyday
> structures provide most members with enough portable benefits
> and security that I don't understand why this outdated
> feature has not been banned! :-)
>
> Joel
Are you kidding? I sure hope so.
Unions provide the only completely portable and reliable method of
supporting polymorphic data structures. Paraphrased real example:
struct common_event {
int event_type;
time_t event_time;
}
struct mouse_down_event {
int event_type;
time_t event_time;
int x, y;
}
struct keyboard_event {
int event_type;
time_t event_time;
int char_code;
}
... etc...
union event {
struct common_event common;
struct mouse_down_event m_event;
struct keyboard_event k_event;
....
}
If you have maybe 80 different event types, it'd be unreasonable to
store all the information in a struct. The above "union event"
construct allows you to test the common portion of the structs via
.common.event_type, before deciding exactly what sort of event it is.
This sort of construct becomes absolutely crucial in object-oriented C
programming.
Note that you cannot portably (i.e., the C Standard does not define
the behavior if you do it) simply cast pointers to these structures
back and forth. GTK+ does it this way, and AFAIK almost no compiler
actually refuses such a construct, but that doesn't mean future ones
won't. As a principle, I always stray from the C standard as
absolutely seldom as possible (only in using system-specific
libraries, headers and features that are necessary).
Micah
|