Unions

Badri Lokanathan badri at valhalla.ee.rochester.edu
Fri Oct 21 10:16:40 AEST 1988


In article <322 at hrc.UUCP>, dan at hrc.UUCP (Dan Troxel VP) writes:
> 
> Except for the memory savings, what are Unions suited for?

Here are two simple examples where I find unions to be very convenient:

(1) Consider an application that involves linked lists, except
    that the value field may have different items. Rather than write
    add/delete routines for each type of item, make the value field to
    be a union of the various types of values and write only one
    add/delete routine. This works best from the viewpoint of memory
    saving if the value field is of approximately same size (for
    instance, a pointer to another structure.)

(2) If you want to implement the adjacency list scheme for a graph from the
    cover of Aho, Hopcroft and Ullman's Design and analysis of algorithms,
    unions are great:

	    		--------------------------------------
	Vertex item  -->| Vertex attributes | ptr to edges   |
	    		--------------------------------------
	Edge item    -->| Edge attributes | ptr to next edge | 
	    		--------------------------------------

	Here one can union the attributes. For instance:

union Adjacency_list {
	struct {
		char name[8];		       	/* Name of vertex   */
		short low;                      /* Low point */
		union Adjacency_list *edges;    /* Ptr to edge list */
	} vert;

	struct {
		union Adjacency_list *v;	/* Other end of this edge */
		short low1;			/* First low point */ 
		short low2;			/* Second low point */ 
		short weight;			/* Weight of edge */
		union Adjacency_list *next;     /* Ptr to next edge */
	} edge;
};
-- 
"It's better to burn out               {) badri at valhalla.ee.rochester.edu
 Than it is to rust-                  //\\ {ames,cmcl2,columbia,cornell,
 But I'll corrode                    ///\\\ garp,harvard,ll-xn,rutgers}!
 Till I turn to dust."                _||_   rochester!ur-valhalla!badri



More information about the Comp.lang.c mailing list