This blog is under construction

Saturday, 19 May 2012

What is a union?

Union is a user defined data type used to store different data members at the same memory location.  The size of union is equal to the size of the largest data member in the given union.  In the case of union, user can read or assign value to one data member at a time.  Below is the general form of an union.

union <tag_name> {
          type data_element1;
          type data_element2;

Consider the following example,
union value {
          int x;
          char ch;

Here, the largest data member in the union is integer variable x(sizeof(int) is 4 bytes). So, the size of union would be 4 bytes.

Example C program using union:

  #include <stdio.h>
  union book {
        char author[100];
        int pages;
        float price; 

  int main() {
        union book b1;
        printf("Enter author name:");
        fgets(, 100, stdin);
        printf("No of pages:");
        scanf("%d", &b1.pages);
        printf("Price of the book:");
        scanf("%f", &b1.price);
        printf("Size of union: %d\n", sizeof(b1));
        printf("Author: %s\n",;
        printf("Pages : %d\n", b1.pages);
        printf("Price : %f\n", b1.price);
        return 0;

  jp@jp-VirtualBox:~/$ ./a.out
  Enter author name:Steve Jobs
  No of pages:540
  Price of the book:45
  Size of union: 100
  Pages : 1110704128
  Price : 45.000000

From the above example, we could see irrelevant output for the given inputs.  This is because, user can access or modify one data at a time in union.  Here, the size of the union is 100 bytes which is the size of the largest data member author in the union book. All the data members of a union uses the same memory location as storage.  So, all data member will have the value of recently updated data member value.  That is the reason, why we are getting correct value for last accessed(written) data member(price).

Example C program to illustrate Union:

  #include <stdio.h>
  union student {  // union definition
        int rollno;
        char name[100];

  int main() {
        union student s1;
        int flag;
        printf("Do you wanna give roll no/name(1/0):");
        scanf("%d", &flag);
        if(flag == 1) {  // input roll no
                printf("Enter your roll no:");
                scanf("%d", &s1.rollno);
        } else if(flag == 0) {  // inputs name
                printf("Enter your name:");
                fgets(, 100, stdin);
        } else {
                printf("You have given wrong input\n");

        /* print the result */
        if (flag == 1) {
                printf("Roll no:%d\n", s1.rollno);
        } else if(flag == 0) {
                printf("Name: %s\n",;
        return 0;

  jp@jp-VirtualBox:~/$ ./a.out
  Do you wanna give roll no/name(1/0):1
  Enter your roll no:6002
  Roll no:6002

No comments:

Post a Comment