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.


How to access union members in C How to access union members in C Reviewed by Mursal Zheker on Sabtu, Januari 11, 2014 Rating: 5

Tidak ada komentar:

Diberdayakan oleh Blogger.