Saturday 27 January 2018

Union in C

The union is just similar to structure, even syntax to declare/define a union is also similar to that of a structure.The only differences is in terms of storage.Each element in a union is called member.
In structure, each member has its own storage location, whereas all members of union uses a single shared memory location which is equal to the size of its largest data member.


Structure vs Union


Union Declaration:

A union is defined by Union keyword .

union player
{
    int m;
    float x;
    char c;
}Player1;


Create union variables:


When a union is defined, it creates a user-defined type. However, no memory is allocated. To allocate memory for a given union type and work with it, we need to create variables.

Here's how we create union variables:

union car
{
  char name[50];
  int price;
};

int main()
{
  union car car1, car2, *car3;
  return 0;
}


Another way of creating union variables is:

union car
{
  char name[50];
  int price;
} car1, car2, *car3;

In both cases, union variables car1, car2, and a union pointer car3 of union car type are created.




Accessing Union Members:


We use . to access normal variables of a union. To access pointer variables, we use -> operator.

In the above example,
price for car1 can be accessed using car1.priceprice for car3 can be accessed using car3->price



Syntax for accessing any union member is similar to accessing structure members,
union test
{
    int a;
    float b;
    char c;
}t;

t.a;    //to access members of union t
t.b;     
t.c;

As like structure, in a similar fashion, we can access Union Members.


Let Us understand the union concept  with a C code:

#include <stdio.h>

union item
{
    int a;
    float b;
    char c;
};

int main( )
{
    union item it;
    it.a = 12;
    it.b = 20.2;
    it.c = 'z';
    
    printf("%d\n", it.a);
    printf("%f\n", it.b);
    printf("%c\n", it.c);
    
    return 0;
}

C compiler to run above code:https://goo.gl/bzuHcQ


Output:
1101109626
20.199940
z

As you can see here, the values of a and b get corrupted and only variable c prints the expected result. This is because in union, the memory is shared among different data types. Hence, the only member whose value is currently stored will have the memory.


In the above example, value of the variable c was stored at last, hence the value of other variables is lost.











No comments:

Post a Comment