Path: utzoo!utgpu!attcan!uunet!lll-winken!lll-tis!helios.ee.lbl.gov!pasteur!ames!mailrus!cornell!rochester!uhura.cc.rochester.edu!ur-valhalla!badri From: badri@valhalla.ee.rochester.edu (Badri Lokanathan) Newsgroups: comp.lang.c Subject: Re: Unions Summary: Two examples. Keywords: What can they be used for? Message-ID: <1532@valhalla.ee.rochester.edu> Date: 21 Oct 88 00:16:40 GMT References: <322@hrc.UUCP> Organization: UR Dept. of Electrical Engg, Rochester NY 14627 Lines: 45 In article <322@hrc.UUCP>, dan@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@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