Back to: C Tutorials For Beginners and Professionals
Union in C Language with Examples
In this article, I will discuss Union in C Language with Examples. Please read our previous article, discussing Structure in C with Examples. A union in C is a user-defined data type that allows storing different data types in the same memory location. It’s similar to a structure, but while a structure allocates enough space to store all its members, a union only allocates enough space to store the largest member. As a result, only one member can be used at a time.
Union in C Language:
A union in the C programming language is a data structure that allows different data types to be stored in the same memory space. It’s similar to a structure but with a key difference: all members share the same memory location in a union. This means a union can contain only one of its declared member’s data at any given time.
No memory is allocated during the definition of the union. Memory is only allocated when its variables are created (usually preceded by the keyword union). The variables of the union types occupy the memory size, which is the maximum size among all its members. The members can be accessed by using the dot (.) operator.
The union is quite similar to the structures in C. The union is also a derived type like a structure. A union can be defined in the same manner as a structure. The keyword used in defining a union is the union, whereas the keyword used in defining a structure is struct.
Syntax of Union in C Language:
Example of Union:
Union variables can be created in a similar manner as structure variables.
In both cases, union variables c1, c2, and union pointer variable c3 of the type union car are created.
Accessing Members of a Union in C:
The members of unions can be accessed in a similar manner as that structure. Suppose you want to access the price for union variable c1 in the above example; it can be accessed as c1.price. If you want to access the price for union pointer variable c3, it can be accessed as (*c3).price or as c3->price.
Note: All the properties of structures apply to a union, like a variable creation, pointer creation, array creation, and typedef approach.
Example to Understand UNION in C Language:
In the below example:
- A union named Data is defined with three members: an integer i, a float f, and a character array str.
- In the main function, the union data is declared, i.e., union Data data;
- The integer member i is set to 10 and printed.
- Then, the float member f is set to 220.5 and printed.
- Finally, the string str is set to “C Programming” and printed.
#include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main () { union Data data; data.i = 10; printf ("data.i : %d\n", data.i); data.f = 220.5; printf ("data.f : %f\n", data.f); strcpy (data.str, "C Programming"); printf ("data.str : %s\n", data.str); return 0; }
Output:
Note: It’s important to note that setting a new member value overwrites the previous member data, as all members share the same memory location. This is why the values of data.i and data.f are invalid after data.str is set. The program’s output reflects the value of the set last member.
Union Examples in C Language:
Below are a few examples illustrating how unions can be used in C.
Type-Punning Example
#include <stdio.h> union TypePunning { float f; unsigned int i; }; int main() { union TypePunning tp; tp.f = 1.0; if (tp.i == 0x3F800000) { printf("The IEEE 754 bit representation of 1.0 is correct.\n"); } else { printf("Unexpected bit pattern.\n"); } return 0; }
This example demonstrates how a float value can be accessed as an int. This is known as type-punning and is useful in low-level programming.
Union Inside a Structure in C Language
#include <stdio.h> typedef enum { INT, FLOAT, STR } DataType; struct Variant { DataType type; union { int i; float f; char str[20]; } data; }; void printValue(struct Variant v) { switch (v.type) { case INT: printf("Integer: %d\n", v.data.i); break; case FLOAT: printf("Float: %f\n", v.data.f); break; case STR: printf("String: %s\n", v.data.str); break; } } int main() { struct Variant v; v.type = INT; v.data.i = 123; printValue(v); v.type = FLOAT; v.data.f = 98.76; printValue(v); v.type = STR; strcpy(v.data.str, "Hello World"); printValue(v); return 0; }
In this example, a union is used within a struct. The structure also contains an enum to keep track of which type of data is currently stored in the union. This pattern is helpful when dealing with variable data types.
Union for Memory-Mapped Hardware Access
#include <stdio.h> union Port { struct { unsigned char low; unsigned char high; } byte; unsigned short int word; }; int main() { union Port port; port.word = 0xABCD; printf("Low byte: 0x%X\n", port.byte.low); printf("High byte: 0x%X\n", port.byte.high); return 0; }
This example is typical in embedded systems where you need to access individual bytes of a hardware register (represented here by a short int).
Difference Between Structure and Union in C
When to Use Union in C Language?
In the C programming language, the union keyword defines a union data type, allowing us to store different data types in the same memory location. Here are some scenarios when you might use a union:
- Memory Efficiency: When you have a large structure with multiple fields but only one field is used at a time, a union can save memory. All members of a union share the same memory location, so the size of its largest member determines the size of a union.
- Type-Punning: Unions allow you to access the same memory as different data types. This is useful for low-level programming tasks, such as interpreting the bytes of a float as an int, or for working with hardware where the meaning of a particular piece of memory might change depending on context.
- Variant Types: When a variable can be of multiple types (but only one type at a time), unions are a good choice. This is common in systems programming, parsers, and network protocols where the data type might vary but is indicated elsewhere (like a type field).
- Memory-Mapped Hardware Access: In embedded and systems programming, unions are used to access hardware registers. Different bits in a hardware register might have different meanings, and a union can be used to access these bits individually or as a whole.
- Serialization/Deserialization: In data serialization, you might use a union to interpret a series of bytes differently depending on the context, which can be useful in network communication or file I/O operations.
- Efficient Storage of Small Data Types: For storing small data types within a larger block of memory, a union can be useful. This is particularly relevant in memory-constrained environments.
Advantages and Disadvantages of using Union in C
Using unions in C programming has its specific advantages and disadvantages. Understanding these can help you decide when using a union over other data structures like structures (structs) is appropriate.
Advantages of Using Union in C Language
- Memory Efficiency: Unions are memory-efficient as they share the same memory space for storing different variables. They only allocate memory for the largest member, which can be beneficial in memory-constrained environments.
- Flexibility: Unions allow different data types to be treated as the same type, which can be useful in various applications like hardware interaction, protocol design, or data type conversions.
- Union with Type Field: A common pattern is to use a union with an accompanying field indicating the type of data it currently holds. This approach can be a powerful way to handle various data types in a uniform manner.
- Use in Complex Data Structures: Unions can be embedded within structures to create complex data structures that can handle multiple data types effectively.
Disadvantages of Using Union in C Language
- Single Value Storage: Since a union can only store one value at a time, it’s unsuitable for situations where you must simultaneously store multiple values of different types.
- Type Safety: Unions do not provide type safety. If a different data type is accessed from the one most recently written, the result can be unpredictable, leading to bugs and errors.
- Debugging Difficulty: Debugging issues with unions can be challenging, especially when the wrong type is accessed, leading to unexpected behavior or corrupt data.
- Limited Use Cases: The use of unions is limited to specific scenarios where their advantages are beneficial. In many cases, other data structures like structs might be more appropriate.
- Portability Issues: The behavior of unions can depend on the system’s architecture, like endianness, which can lead to portability issues across different platforms.
In the next article, I will discuss the Difference Between Structure and Union in C Language with Examples. In this article, I try to explain the Union in C Language with Examples. I hope you enjoy this Union in C Programming Langauge with Examples article. I would like to have your feedback. Please post your feedback, questions, or comments about this article.