Wednesday, October 13, 2010

How to Use Union in C Programming

,



Union is a derived datatypes which group together a number of variable . Union is like a structure in c language which used to store one of a set of different types. A union holds the value of one-variable at a time. C Programming provide this facility which help to share same memory with different different variables. Accessing members of a union is via “.” member operator or, for pointers to unions, the -> operator.

union syntax in c :

union union_name
 {
  <datatype> first_element 1;
  <datatype> first_element 2;
  <datatype> first_element 3;
 };


Examples of  Union in C language

#include <stdio.h>
#include <conio.h>

union tech
{
 int i;
 char name[50];
};

void main()
{
  union tech a;
  printf("\n\t Enter developer id : ");
  scanf("%d", &a.i);
  printf("\n\n\t Enter developer name : ");
  scanf("%s", &a.name);
  printf("\n\n Developer ID : %d", a.i);//Garbage
  printf("\n\n Developed By : %s", a.name);
  getch();
}

0 comments to “How to Use Union in C Programming”

Post a Comment