C UNION
In C, Union is a user-defined data type. Each union member has access to the same memory location.
A union can have numerous members, but only one of those members can ever have a value present. Unions offer a practical means of serving several purposes with the same memory space
Syntax for defining union:
union complex
{
int real;
char img[40];
};
Code:
#include "stdio.h"
union Data {
int a;
float b;
char test[25];
};
int main( )
{
union Data temp;
temp.a = 1;
temp.b = 2.4;
strcpy( temp.test, "This is test message");
printf( "temp.a : %d\n", temp.a);
printf( "temp.b : %f\n", temp.b);
printf( "temp.test : %s\n", temp.test);
return 0;
}
Output:
temp.a : 1936287828
temp.b : 18492449856613858175293792976896.000000
temp.test :This is test message
temp.b : 18492449856613858175293792976896.000000
temp.test :This is test message
Explanation:
Define a union variable using the syntax. We employ the member access operator to gain access to any union member (.). Between the name of the union variable and the union member that we want to access, the member access operator is coded as a period.