Subj : Re: Why not unions To : comp.programming From : Rob Thorpe Date : Wed Jul 27 2005 01:00 pm Shwetabh wrote: > Hi, my question is related with data structures. > Why are only structures used for implementing data structures. > Why not unions when they are more memory efficient than structures. > > Thanks in advance In C there are two main uses of unions: 1. To save space by using a single location to store many types of data. 2. To allow a piece of data to be accessed in more than one way. For instance copied somewhere as a string, then used as a series of floats. #2 is highly-system dependant and difficult to debug, it's still used in some circumstances. It's only very rarely needed. In case #1 the increase in the size of memory means that unions aren't often necessary. Even if they would be, there's another approach that may be better. For example, lets say we have a struct like this: union bar { int x; double y; } struct foo { enum thing what_it_is; union bar b; } foo.what_it_is describes what is in the union b, it could have values DOUBLE or INT for example. It's only worth making this a union if we need the space. If we don't then we could use: struct foo { enum thing what_it_is; int x; double y; char *z; } Which is simpler and easier to check. But even if space is important we can do better, instead of making the union "bar" specialised to our specific need it can be general. union in_var_t { long i; double d; char *s; void *p; } struct var_t { enum var_types what; union in_var_t x; } This struct "var_t" is a variant, it can be used to represent any reasonably simple type anywhere in the program. A set of functions or macros can be written to access the type without needing to use the fields (making it an object), these can also provide error checking. Outside of C there are many languages with direct support for variants. .