3

Possible Duplicate:
C: Where is union practically used?

I know the concept of union but I don't see the actual case in real world coding that I should use union data structure. I will be very appreciated if you guys can give me some examples or tutorials that shows cases using union properly.

Thanks in advance.

Community
  • 1
  • 1
codereviewanskquestions
  • 13,460
  • 29
  • 98
  • 167

2 Answers2

3

Imagine having a struct that keeps a value and the type of that value. When the type is set to a particular type, you would only need to use one of the members of the union rather than waste space for three of them when you use only one simultaneously.

struct {
  int type;

  union {
    int intval;
    double dval;
    char cval;
  } value;
}
Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130
2

Where I use it constantly: parsing a configuration file I store all values in a union data type. E.g. when values can be int types or strings, I would use a data structure as follows:

struct cval_s {
  short type;
  union {
    int ival;
    char *cval;
  } val;
};

In complexer problems, I use them, too. E.g. once I wrote an interpreter for an easy scripting language, and a value in this language was represented by a struct containing a union.

ckruse
  • 9,642
  • 1
  • 25
  • 25