C programming - union

In C programming, a union is a user-defined composite data type that allows different data types to be stored in the same memory location. Unlike a struct, a union can only hold the value of one member at a time. The memory allocated to a union is large enough to hold the largest member of the union.

To define a union in C, you use the union keyword followed by a name for the union and a set of member declarations enclosed in braces. For example, the following code defines a union named MyUnion that contains three members: myInt, myFloat, and myChar.

‮efer‬r to:theitroad.com
union MyUnion {
    int myInt;
    float myFloat;
    char myChar;
};

To declare a variable of a union type, you simply use the union name followed by the variable name. For example, the following code declares a variable named myUnion of type MyUnion:

union MyUnion {
    int myInt;
    float myFloat;
    char myChar;
};

union MyUnion myUnion;

You can access the members of a union using the dot (.) operator. However, you can only access the member that is currently stored in the union. For example, to set the myInt member of myUnion, you would use the following code:

union MyUnion {
    int myInt;
    float myFloat;
    char myChar;
};

union MyUnion myUnion;

myUnion.myInt = 10;

union variables can be passed as arguments to functions and returned from functions, just like any other data type.

union variables are commonly used in low-level programming when you need to store different types of data in the same memory location. They can also be used to save memory by allowing you to reuse the same memory location for different purposes. However, you should be careful when using union variables because it can be easy to accidentally access the wrong member if you're not careful.