Unions

Unions are similar to structures but only one member within the union can be used at a time, due to it having a shared memory for all members.

 

union Publication {

char name[20] ;
float price ;
int pages ;
};

 

Unions are used when justĀ one condition will be applied and only one variable is required.

 

#include <stdio.h>

union Articles
{
   char desc[30];
   float price;
   int devs;
} linux = {"fun, free and better!"} ;

int main( )
{

   printf("The best OS is %s ", linux.desc);

   /*set price - remembering that a union can only hold one variable at a time*/
   linux.price = 0.01 ;
   printf("It costs less than $%2.2f ", linux.price);

   linux.devs = 1200 ;
   printf( "and has about %d developers on each release!", linux.devs);

   return 0;
}

Compile & Run:

The best OS is fun, free and better! It costs less than $0.01 and has about 1200 developers on each release!

Leave a Reply