Union in C Language

Posted on

Union in C

Union in C Language

 

A union is kind of just like the constructions in C. It additionally retailer totally different knowledge sorts in the identical reminiscence location. It’s also a person outlined knowledge sort similar like construction.

 

union and construction are nearly similar

Construction Union

Defining a union

Union might be outlined in similar method as constructions, for outlining union use union key phrase the place as for outlining construction use struct key phrase.

Syntax

Instance of Union


Accessing members of an union

The member of unions might be accessed in comparable method as Construction with union reference. Suppose, we you need to entry identify variable in above instance, it may be accessed as u.identify.


Benefit of union over construction

It occupies much less reminiscence as a result of it occupies the reminiscence of largest member solely.

Drawback of union over construction

It could retailer knowledge in a single member solely.


Distinction between Construction and Union

Construction Union
1 For outlining construction use struct key phrase. For outlining union we use union key phrase
2 Construction occupies extra reminiscence house than union. Union occupies much less reminiscence house than Construction.
3 In Construction we will entry all members of construction at a time. In union we will entry just one member of union at a time.
4 Construction allocates separate space for storing for its each members. Union allocates one frequent space for storing for its all members. Union discover which member want extra reminiscence than different member, then it allocate that a lot house

Reminiscence Allocation in Construction and Union

Construction allocates separate space for storing for its each members. Union allocates one frequent space for storing for its all members. Union discover which member want extra reminiscence than different member, then it allocate that a lot house

In case of Construction

Syntax

Instance

In case of Union

Syntax

For above union, solely 8 bytes of reminiscence shall be allotted as a result of double knowledge sort will occupy most house of reminiscence over different knowledge sorts.
Complete reminiscence allocation = 8 Bytes


When use Construction and Union

When want to govern the info for all member variables then use construction. When want to govern just one member then use union.

Be aware:

  1. All of the properties of the construction are similar for union, besides initialization course of.
  2. In case of construction initialize all knowledge members at a time as a result of reminiscence location are totally different however in case of union just one member must be initialize.
  3. In case of union if we initializing a number of member then compiler will provides an error.

Instance of Union in C

Output