In C, a union is a particular data type that allows several data types to be stored in the same memory address. A union can have numerous members, but only one can have value at any moment. Unions allow you to use the same memory space for multiple purposes more effectively.
You must use the union statement the same way you would when constructing a structure to define a union. The union statement creates a new data type for your application with many members. The following is the format for the union statement:
The union tag is optional, and each member definition is a standard variable definition, such as int I float f; or any other valid variable declaration. You can provide one or more union variables before the last semicolon at the conclusion of the union's declaration, although this is optional. This is how you would create a Data union type with three members: If, and str.
An integer, a floating-point number, or a string of characters can now be stored in a Data type variable. It indicates that a single variable, i.e., the same memory address, may be used to hold a variety of data kinds. Depending on your needs, you may utilize any built-in or user-defined data types inside a union.
A union's memory will be vast enough to store the union's most powerful member. For example, in the preceding example, Data type will take up 20 bytes of memory space
since a character string can only take so much space. The following example shows how much memory the union, as mentioned above, takes up in total.
|