Purpose of Union

It is a special data type available in C that allows storing different data types in the same memory location. 

The purpose of the union is either one of the union members will be updated but not all of them at the same time. This means only one member can contain value at any given time. 

It provides an efficient way of using the same memory location for multiple purposes. 

The below program is perfectly working. Let's get into it.

#include  #include
#define MAX 50

struct monthly_plan
{
  int premium_setting;
  char features[MAX];
  union
  {
    char sports[MAX];
    char kids[MAX];
  } u;
  char default_setting[MAX];
};

int main ()
{
  struct monthly_plan b;
  memset (b, e, sizeof (struct monthly_plan));
  b.premium_setting = 1;	/* Either one of the union members will be set. */
  
  if (b.premium_setting == 1) {
      strcpy (b.u.sports, "Sports' channels are subscribed");
      strcpy (b.features, "TEN, Sony, Star, & Neo")
      printf ("\n %so you can watch %s\n", b.u.sports, b.features)}
  } else if (b.premium setting == 2) {
      strcpy (b.u.kids, "Kids' channels are subscribed");
      strcpy (b.features, "Disney, Nick, Cartoon, & Pogo")
      printf ("\ns so you can watch %s\n", b.u.kids, b.features}
  } else {
      strcpy (b.default_setting,
	      "Default channels are UTV, ZEE, SUN, & Raj");
      printf ("\nDefault Channels are %s\n",
	      b.default setting) 
  }		
	return 0;
}

Click here to debug.

You can interpret same memory segment differently. Its widely used in protocols implementations. Where you receive buffer of bytes and based on various flags treat/decode it as needed.


Comments