what is union in c

what is union in c

1 year ago 87
Nature

A union is a special data type available in C that allows storing different data types in the same memory location. It is a collection of variables of different data types in the same memory location. Unions provide an efficient way of using the same memory location for multiple purposes. The syntax to declare a union is with the union keyword, and it can have numerous members, but only one of them can contain a value at any given time. The size of the union will always be equal to the size of the largest member of the array. To access the fields of a union, use the dot (.) operator, i.e., the variable name followed by the dot operator followed by the field name.

Here is an example of a union declaration in C:

union Data {
   int i;
   float f;
   char str;
};

In this example, the union Data has three members: an integer i, a float f, and a character str. At any given time, only one of these members can contain a value.

Here is an example of how to create a union variable and initialize its members:

union car {
   char name;
   int price;
};
int main() {
   union car car1, car2, *car3;
   car1.name = A;
   car2.price = 10000;
   car3 = &car1;
   printf("%c\n", car3->name);
   printf("%d\n", car2.price);
   return 0;
}

In this example, we create a union car with two members: a character name and an integer price. We then create three union variables car1, car2, and car3. We initialize the name member of car1 to A and the price member of car2 to 10000. We then assign the address of car1 to car3 and use the arrow operator (->) to access the name member of car3 and the price member of car2.

In summary, a union in C is a user-defined data type that allows storing different data types in the same memory location. It provides an efficient way of using the same memory location for multiple purposes. The syntax to declare a union is with the union keyword, and it can have numerous members, but only one of them can contain a value at any given time. To access the fields of a union, use the dot (.) operator.

Read Entire Article