This blog is under construction

Saturday, 11 January 2014

How to access union members in C

Dot operator is used to access(or assign) the data members of a union variable.  Consider the following example,

union value {
         int x;
         float y;
};

union value obj;
Here, obj is a union variable of type union value.  x and y are data members of the union value. Let us see how to assign value to or access data members of union using dot operator.

obj.x = 10;

The above statement assigns value 10 to the data member x of the union variable obj.

obj  - object name(union variable name)
x     - data member in union value
.     - dot operator


Example C program to illustrate accessing union members using dot operator

  #include <stdio.h>
  union value {
        int x;
        float y;
  }obj;

  int main() {
        obj.x = 5;
        printf("Value of x is %d\n", obj.x);
        obj.y = 19.22;
        printf("Value of y is %f\n", obj.y);
        printf("Value of x is %d\n", obj.x);
        return 0;
  }


  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Value of x is 5
  Value of y is 19.219999
  Value of x is 1100595855


The value of data member y overwrites the value of x and that is reason why we see junk value in x.  Basically, all data members in a union shares same storage place.


2 comments:

  1. This blog awesome and i learn a lot about programming from here.The best thing about this blog is that you doing from beginning to experts level.

    Love from

    ReplyDelete