Cover Image for C Union
104 views

C Union

The union is a user-defined data type that allows you to store different types of data in the same memory location. It is similar to a struct in that it can hold multiple members, but unlike a struct, where each member has its own memory space, all members of a union share the same memory location. As a result, a union can only hold the value of one of its members at any given time. Unions are often used when you need to save memory and when you know that only one of the members will be accessed or modified at any given time.

Here is the syntax for defining a union in C:

C
union UnionName {
    member1_type member1_name;
    member2_type member2_name;
    // Additional members
};
  • UnionName is the name of the union.
  • member1_type, member2_type, etc., are the data types of the members.
  • member1_name, member2_name, etc., are the names of the members.

Here’s an example of a union:

C
#include <stdio.h>

union MyUnion {
    int integer;
    double floating_point;
    char character;
};

int main() {
    union MyUnion u;

    u.integer = 42;
    printf("Value as integer: %d\n", u.integer);

    u.floating_point = 3.14;
    printf("Value as floating point: %f\n", u.floating_point);

    u.character = 'A';
    printf("Value as character: %c\n", u.character);

    return 0;
}

In this example, we define a union MyUnion with three members of different data types (int, double, char). We can assign values to any one of these members at a time, but only one member can be active at a given moment. When we change the value of one member, it can affect the interpretation of other members since they share the same memory location.

It’s important to use unions carefully, as they can lead to data type-related issues if not handled properly. Developers often use unions when dealing with binary file formats, low-level hardware access, or situations where memory optimization is crucial.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS