Understanding of Union and Struct in Data Type

More
2 years 6 months ago - 2 years 6 months ago #1 by rohanjoshi0894 Understanding of Union and Struct in Data Type was created by rohanjoshi0894
Hi Arjun,

I want to give answer's of your question the difference between Structure and Union. As these two are the user-defined data types.

Difference Between Structure and Union

1. Keyword

The keyword ‘struct’ is used to define a structure whereas ‘union’ keyword is used to define a union.

2. Memory Allocation

Separate memory space is allotted for the members within a structure and members have different addresses that do not share memory. A union, on the other hand, shares the same memory space for all its members so shared memory location is allocated.

3. Member Access

A union stores a single value at a time for all its members making accessibility to only one member at a time. While multiple values can be stored in a structure so any member value can be accessed and retrieved at any time.

4. Size

The size of a structure is equal to the sum of the size of all members or more, whereas the size of a union is equal to the size of the largest size member.

5. Initialization

In a structure, several members can be initialized at once, while in a union, only the first member can be initialized with the value of its type.

5. Value

A structure can store different values of all the members and change in the value of one member will not have any effect on the values of other members. While a union stores same value for all its members and change of value of one member will affect the value of other.

Here is the coding example:

Structure:

struct Person
{
int height;
double weight;
}

Union:

union Person {
int height;
double weight;
}

To know more and the benefits of these user-defined data types, you can read out this post .
Last edit: 2 years 6 months ago by rohanjoshi0894.

Please Log in or Create an account to join the conversation.

We use cookies

We use cookies on our website. Some of them are essential for the operation of the site, while others help us to improve this site and the user experience (tracking cookies). You can decide for yourself whether you want to allow cookies or not. Please note that if you reject them, you may not be able to use all the functionalities of the site.