Showing posts with label UNIONS. Show all posts
Showing posts with label UNIONS. Show all posts

Friday, 11 January 2019

UNIONS


UNIONS
Unions are similar to structures except the fact that memory allocated for a union variable is memory required for the largest field.
The only difference between the structure and union is memory allocation.
Syntax:
          Union unionname
          {
                   Datamember1;
                   Datamember2;
          };

Example

#include<stdio.h>
#include<conio.h>
union emp
{
          char name[25];
          int idno;
          float salary;
}e1;
void main()
{
          printf("Size of union is %d",sizeof(e1));
}

Output
Size of union is 25

Example
#include<stdio.h>
#include<conio.h>
union emps
{
          double a;
          float b[2];
          char c[8];
}e1;
void main()
{
          int i;
          clrscr();
          e1.a=1355.674;

          e1.b[0]=2.3;
          e1.b[1]=4.5;

          printf("Enter 8 characters string:");
          for(i=0;i<8;i++)
                   scanf("%c",&e1.c[i]);
          printf("%.3lf\n",e1.a);
          printf("%.2f,%.2f\n",e1.b[0],e1.b[1]);
          for(i=0;i<8;i++)
                   printf("%c\n",e1.c[i]);

          getch();
}
Output:
Enter 8 characters string: asdgghjk
2.713061780997133810000000000000000000000e+209
1078827923249377390000000.00,283381667918681262000000000.00a
s
d
g
g
h
j
k

it allocates memory only to the largest data type size. In this situation it allocates memory to string, the rest two values double and float values are garbage values.