union in c

It is user defined data type same as structure where property share same location of memory.
 

Declaration of union

union Data{
int x;
int y;
};
 

Create object of union

union Data d;

Access property of union

d.x=100

Example

#include <stdio.h>
union Data{
  int x;
  int y;
};
union Data d;
int main() {
  d.x= 100;
  printf("x:%d \n", d.x);
  printf("y:%d \n", d.y);
  
  d.y=d.y+100;
  
  printf("y:%d \n", d.y);
  printf("x:%d \n", d.x);
    return 0;
}
© 2016 - 2022, All Rights are Reserved.