l i n u x - u s e r s - g r o u p - o f - d a v i s
L U G O D
 
Next Meeting:
November 4: Social gathering
Next Installfest:
TBD
Latest News:
Oct. 24: LUGOD election season has begun!
Page last updated:
2001 Dec 30 16:47

The following is an archive of a post made to our 'vox mailing list' by one of its subscribers.

Report this post as spam:

(Enter your email address)
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


LinkedIn
LUGOD Group on LinkedIn
Sign up for LUGOD event announcements
Your email address:
facebook
LUGOD Group on Facebook
'Like' LUGOD on Facebook:

Hosting provided by:
Sunset Systems
Sunset Systems offers preconfigured Linux systems, remote system administration and custom software development.

LUGOD: Linux Users' Group of Davis
PO Box 2082, Davis, CA 95617
Contact Us

LUGOD is a 501(c)7 non-profit organization
based in Davis, California
and serving the Sacramento area.
"Linux" is a trademark of Linus Torvalds.

Sponsored in part by:
O'Reilly and Associates
For numerous book donations.