I never really got this back in school when I learned C programming and the instructor did a bad job explaining it. What is a union in C really and how do you use it?

union in C/C++ is basically a mechanism to store more than one of variable at a given memory location. It has a variety of uses. Look here and here.

The short story is that a union is like a structure except each member shares the memory. The result is that a union takes up less space, but you're also restricted to using a single member at a time.

Here is a simple example of a union

union items
{
    short apples;
    long  oranges;
    float  amount;
};

your program, not the compiler, is responsible for making sure the items in the union are referenced correctly. If you instantiate an object of type items and set amount to something, then that object should always reference amount and not one of the other union members. The compiler will not complain if you do, but it will result in unexpected behavior. You can, of course, assign one of the other values a value and use that member variable from then on.

Some unions I have worked with are inside another structure that the structure contains an int that indicates which union member is in use.

const int UNDEFINED_VALUE = 0;
const int APPLES_VALUE = 1;
const int ORGANGES_VALUE = 2;
const int AMOUNT_VALUE = 3;
struct items
{
    int    n;
    union 
    {
        short apples;
        long  oranges;
        float  amount;
    };
};

In the above n would be one of the four const values shown above and the program would always know which union member is active at the time it is referenced.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.