Understanding of Union and Struct in Data Type

  • Posts: 3
1 month 3 weeks ago #1 by arjunkumar
Hello Everyone, I am learning c programming and i am confused to understand the difference in Union and Struct in data type. As such struct is used for storing various data types that when aggregated, represent a user-defined data type but I don't know about the union. Can anyone know about the main difference between them?
The following user(s) said Thank You: rohanjoshi0894

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

  • Posts: 1
1 month 3 weeks ago - 1 month 3 weeks ago #2 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 .

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