Thread: Unions

  1. #1
    Registered User Nutshell's Avatar
    Join Date
    Jan 2002
    Posts
    1,020

    Unions

    Hi,

    I don't quite understanding what is a union. Pls tell me what it is and where it's used on. My book says that a union shares the space of variables, but i don't understand that, what does it mean sharing the space, how is it shared.

    thnx

  2. #2
    Registered User Nutshell's Avatar
    Join Date
    Jan 2002
    Posts
    1,020
    well, but what's its use?

  3. #3
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Originally posted by Nutshell
    well, but what's its use?
    When you want 1 region of memory to represent multiple data types

  4. #4
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    Code:
    union A
    {
        int data1;
        char data2;
        unsigned char data3;
    };
    The variables data1, data2 and data3 share memory. The block of memory they share has the size of the largest datastructure in the union. In this example data1 is the largest datastructure and so a variable of type union A can store at most an integer type.

    Since data1, data2 and data3 share the same block of memory, changing one of the variables implies changing the others too.

    Assume N is the block of memory which is a variable of type union A. Also assume we are working on a machine where an integer is 16 bits. The member data1 of union A fits exactly in the memory block, it is of type int, but the other two variables are just the half of data1.

    Code:
    N         - XXXX XXXX XXXX XXXX
    ---------------------------------------
    data1  - XXXX XXXX XXXX XXXX
    data2  - XXXX XXXX
    data3  - XXXX XXXX

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unions of the same size and pointers
    By holychicken in forum C Programming
    Replies: 9
    Last Post: 10-06-2008, 03:29 PM
  2. Structures, Unions and Classes
    By Makoy in forum C++ Programming
    Replies: 2
    Last Post: 02-23-2004, 02:57 PM
  3. Structures - Unions
    By AProg in forum C Programming
    Replies: 16
    Last Post: 05-27-2003, 12:43 AM
  4. unions problems!
    By nextus in forum C++ Programming
    Replies: 3
    Last Post: 01-12-2003, 04:04 AM
  5. Unions in c++
    By The Gweech in forum C++ Programming
    Replies: 5
    Last Post: 08-06-2002, 08:14 AM