Saturday, May 2, 2015

C Program on Union


#include
union tag
{
 int a;
 char ch;
 };
 void main()
 {
  union tag ob;
  clrscr();
  printf("\nEnter age:");
  scanf("%d",&ob.a);
  printf("\nEntered age=%d",ob.a);
  ob.ch='m';
  printf("\nGender=%c",ob.ch);
   printf("\nNow age=%d",ob.a);
  getch();
  }

  Just watch the output, if you have entered 20 as age, the first output will show 20 next you have set value 'm' on union member 'ch'. As union members share the same location, so the age value is destroyed.

 Output for gender will display 'm' but the third output will show wrong value.

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner