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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#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! |