C - Union
Union is a user-defined data type that allows you to store different types of data in the same memory location. It enables you to allocate memory for a variable that can hold one of several possible data types, but only one at a time. Here's an explanation of unions in C:
Union Declaration:
To define a union, you use the union keyword followed by the name of the union and a list of member variables enclosed in curly braces.
union unionName {
dataType member1;
dataType member2;
// ...
};
unionName: The name given to the union.
dataType: The data type of each member variable.
#include <stdio.h>
// Union declaration
union Data {
int intValue;
float floatValue;
char stringValue[20];
};
int main() {
// Union variable declaration
union Data data;
// Accessing and modifying union members
data.intValue = 10;
printf("Value: %d\n", data.intValue);
data.floatValue = 3.14;
printf("Value: %.2f\n", data.floatValue);
strcpy(data.stringValue, "Hello");
printf("Value: %s\n", data.stringValue);
return 0;
}
In this example, a union named Data is defined with three member variables: intValue (an integer), floatValue (a float), and stringValue (a character array). Inside main(), a union variable data is declared, and its members are accessed and modified. Notice that the memory allocated for the union is shared by all its member variables.
Since a union can hold only one value at a time, accessing a member variable should be done carefully. Changing the value of one member will modify the value of all other members sharing the same memory location.