Unions

0 bookerisq70498 November 13, 2020

In the previous tutorials, We have learned about the structure. 

Unions are similar to the structure. Its syntax and use are similar to the structure. It also contains members whose individual data types may differ from one to another. 

The difference is that all members within the union share the same storage area of computer memory, whereas each member within a structure is assigned its own unique storage.

We will also talk about the difference between union and structure. At right now, We will look one example.

void main()
{
    union student
    {
        int roll;
        float marks;
    }

    union student std;

    st.roll = 20;
    printf("Roll = %d", std.roll);

    st.marks = 99;
    printf("\nMarks = %f", std.marks);
}

The output of the above program is:

Roll = 20
MArks = 78.000000

If two members are used simultaneously, the output is unexpected as following

void main()
{
    union student
    {
        int roll;
        float marks;
    }

    union student std;

    st.roll = 20;
    st.marks = 99;

    printf("Roll = %d", std.roll);
    printf("\nMarks = %f", std.marks);   
}

The output of the above program is:

Roll = 0
MArks = 78.000000

Here, the roll is zero as memory is replaced by another variable std.marks.

Difference Between Structure and Union

StructureUnion
1) Each member within a structure is assigned its own unique storage. It takes more memory than a union.1) All members within the union share the same storage area of computer memory. It takes less memory than structure.
2) The amount of memory required to store a structure is the sum of the size of all members.2) The amount of memory required to store a union is the same as a member that occupies the largest memory.
3) All the structures can be accessed at any point in time.3) Only one member of the union can be accessed at any given time.