5 Years
Discussion Span
Last Post by deceptikon

where is union required?

A union is never required, but it can simplify certain tasks such as type punning. An example is from the C standard library implementation in my signature. I use a union for punning between an IEEE double, its 64-bit representation, and a breakdown of the key components (specified by bitfields):

typedef union _real8 {
    unsigned long long ivalue;
    double             fvalue;
    struct {
        unsigned long long mantissa : 52;
        unsigned long long exponent : 11;
        unsigned long long sign     : 1;
    } parts;
} _real8_t;

This saves me from having to use the bitwise operators to break down the value manually such as in this helper function:

        Implementation helper for the fpclassify macro for double/long double.
int _fpclassifyd(double value)
    _real8_t fpv;

    fpv.fvalue = value;

    if (fpv.parts.exponent == 0)
        return fpv.parts.mantissa == 0 ? FP_ZERO : FP_SUBNORMAL;
    else if (fpv.parts.exponent == 0x7FF)
        return fpv.parts.mantissa == 0 ? FP_INFINITE : FP_NAN;

    return FP_NORMAL;

The alternative would be much uglier and harder to infer the intended meaning of the code.

please explain with an example where having union is a better choice than any data structure.

This question is confusing, and I suspect you're using "data structure" to mean C's struct. Keep in mind that "data structure" is used elsewhere in computer science to mean a more general way of storing and accessing data (eg. linked lists, trees, stacks, queues).

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.