as

Thursday, 13 November 2014

Unions In C

Structure occupies the memory size that is equal to the sum of sizes of all members of the structure.

But Union occupies the memory size that is equal to the size of the largest member of the Union.

As shown in below image, total memory occupied by employee union is 6 bytes. If it was structure, memory occupied would have been 8 bytes.


Example –
Below structure will occupy 52 bytes. But if it was union, it would have occupied 50 bytes.
struct Department
{
    int dept_id;
    char dept_name[50];
};



#include<stdio.h>
#include<string.h>            

union u                                           // Here is declare the union.
{
   int a;                                        //veriable declaration.
   float b;
   char  s1[17];
};
             
int main( )
{
   union u u;                                    // here is call the union.     
   system("cls");
   u.a = 8;                                      //
   printf( "u.a : %d\n", u.a);
              
   u.b = 99.0;
   printf( "u.b : %f\n", u.b);
              
   strcpy( u.s1, "fortitude");
   printf( "u.s1 : %s\n", u.s1);
   getchar();
}
           





No comments:

Post a Comment

Leave your valuable feedback. Your thoughts do matter to us.

Sponsored Links

Popular Posts

Comments

ShareThis