Unions
A union is a special data type that stores different data types in the same memory location. Unions are similar to structures in that a union can be defined with many members, but only one member can contain a value at any given time.
Declaring, and Initialising Unions
Unions are defined and declared in the same fashion as structures however the keyword union is used instead of struct. The union is created only as big as necessary to hold its largest data member. A union can be initialised on its declaration but because only one member can be used at a time, only one member can be initialised. Unions initialised with a brace-enclosed initialiser only initialise the first member of the union but individual members can be initialised by using a designated assignment value(see initialising structures). The format and initialisation of the union statement are as follows:
#include <stdio.h> int main( void ) { union shared_tag { char c; int i; float f; double d; } shared={33}; printf("%c character value",shared.c); printf("\n%d integer value ",shared.i); printf("\n%f float value",shared.f); printf("\n%d double value",shared.d); shared.i = 33; printf("\n%c",shared.c); printf("\n%i",shared.i); printf("\n%f",shared.f); printf("\n%f",shared.d); shared.d = 33.333333333333; printf("\n%c",shared.c); printf("\n%i",shared.i); printf("\n%f",shared.f); printf("\n%f",shared.d); return 0; }
Individual union members can be accessed by using the member operator however, only one union member should be accessed at a time.
Unions and Pointers
Unions like structures can be accessed and manipulated by pointers and are declared by preceding the variable name with an asterisk. The individual member variables can be accessed by using the → operator
#include <stdio.h> int main(void) { union data { char c[10]; int i; }; union data charvalue={"union data"}; union data *ptrcharvalue; ptrcharvalue=&charvalue; union data intvalue={13}; union data *ptrintvalue; ptrintvalue=&intvalue; printf("%s", ptrcharvalue->c); printf("\n%i",ptrintvalue->i); return 0; }
This union can hold either a character value c or an integer value i but only one value at a time.