Thread: union

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    70

    union

    Where is a union used, i mean what is the use of a union?

  2. #2
    pronounced 'fib' FillYourBrain's Avatar
    Join Date
    Aug 2002
    Posts
    2,297
    if you want a chunk of memory that can be used in more than one way, you can use a union to accomplish this.

    for instance lets say you want a long (4 bytes) but you also want to be able to easily access each of the 4 bytes you could do a union of a long and a 4 char struct.

    as always there are of course other ways to do this but union is a nice one in some cases.
    "You are stupid! You are stupid! Oh, and don't forget, you are STUPID!" - Dexter

  3. #3
    Registered User
    Join Date
    May 2004
    Posts
    127
    Quote Originally Posted by studentc
    Where is a union used, i mean what is the use of a union?
    Unions are used for reducing storage costs, accessing data with different internal representations, and creating a poor man's polymorphism.

    Reducing storage costs entails exactly what you would think. Instead of using separate memory blocks for objects that will not exist simultaneously, you place them in a union and only use one at a time to save space. Accessing data with different internal representations was already described previously by FillYourBrain, so I won't go into further detail unless you want me to. The poor man's polymorphism is fairly simple. You use a structure with two members: a type identifier and a union of the different types. The union shares storage among different objects and the type identifier tells which object is in use at the time. This also saves space, but the intention is a heterogeneous data type rather than space efficiency.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sizeof union question
    By noops in forum C Programming
    Replies: 13
    Last Post: 06-06-2008, 11:56 AM
  2. Replies: 16
    Last Post: 10-29-2006, 05:04 AM
  3. "generic" union or something
    By Raven Arkadon in forum C++ Programming
    Replies: 2
    Last Post: 12-05-2005, 09:55 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Sorting a Union
    By andy in forum C Programming
    Replies: 4
    Last Post: 11-21-2001, 10:12 AM