Home | API | MFC | C++ | C | Previous | Next

Programming With C

C Unions

A union is a special data type 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 only one member can be used at a time. 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:

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, like structures, by using the member operator ( . ). However, there is an important difference in accessing union members. 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 then be accessed by using the -> operator

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 it can hold only one value at a time.


Home | API | MFC | C++ | C | Previous | Next
The Basics | Variables | Constants | Expressions and Operators | Controlling Program Flow | Input & Output | C++ Functions | Arrays | Characters and Strings | String Manipulation | Pointers | Structures | Unions | File Input and Output | Advanced Pointers | Type Conversion | Dynamic Memory Allocation

Last Updates:25 October 2022