1

I read this link what-is-the-point-behind-unions-in-c But this answer doesn't look enough to me.

Can I have more explanations about uses of unions. I don't want any memory related examples like, this will take max 4 bytes (float occupy 4 bytes ).

union un{
    char ch;
    int iNum;
    float fNum;
};

So my question is,

what exactly the use of union?

why we need this?

Please help me, its confusing me. Thanks.

Community
  • 1
  • 1
user2322888
  • 75
  • 1
  • 4
  • 3
    Please search before posting questions... – RedX Sep 18 '13 at 14:56
  • The accepted answer mentions _variant datatype_. In which isn't it enough? An example? A stack data structure. – mouviciel Sep 18 '13 at 14:59
  • @Dayalrai...thanks a lot ! – user2322888 Sep 18 '13 at 15:00
  • The truth is, we don't 'need' unions. They are useful for saving memory, but if you didn't care about saving memory you could replace every union with a struct and get similar logical behavior. – Jeremy Friesner Sep 18 '13 at 15:04
  • 2
    @JeremyFriesner Unions are useful for type-punning, which cannot be emulated with your suggestion of replacing `union` by `struct`. I think the type-punning use of unions was official in C90 (I am not a specialist of C90), and it was made official again in C99TC3 (footnote 82) and in C11. – Pascal Cuoq Sep 18 '13 at 15:08
  • @PascalCuoq I agree, but type-punning can also be achieved via other means. – Jeremy Friesner Sep 18 '13 at 15:55

2 Answers2

3

Probably the two most common uses for a union are:

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
1

It's good if you have a variable which can be either a char, or a int, or ...

It's often used inside structures that contain the actual type of the union. Often used by parsers to return a token from the lexer. Something like:

struct token
{
    int token_type;

    union
    {
        char  *s;  /* For string or keyword tokens */
        double f;  /* For floating point tokens */
        long   i;  /* For integer tokens */
    } token_value;
};

In the above structure, the used member in the token_value member depends on the token_type member.


Unions can also be used by misusing the data in the union, where you set one member of the variable and read another. This can, for example, be used to convert a floating point number to a series of bytes.

Like

union data
{
    char data[sizeof(double)];
    double value;
};

By setting the value member, you can read the separate bytes of the double value without typecasting or pointer arithmetic. This is technically implementation defined behavior, which means that a compiler may not allow it. It is very commonly used though, so all current compilers allow it.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621