Union in C Language

Posted on

Union in C

Union in C Language

 

A union is kind of just like the buildings in C. It additionally retailer totally different knowledge varieties in the identical reminiscence location. It is usually a person outlined knowledge kind identical like construction.

 

union and construction are virtually identical

Construction Union

Defining a union

Union may be outlined in identical method as buildings, 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 may be accessed in related method as Construction with union reference. Suppose, we you need to entry title variable in above instance, it may be accessed as u.title.


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 will possibly 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 area than union. Union occupies much less reminiscence area 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 cupboard space for its each members. Union allocates one widespread cupboard space for its all members. Union discover which member want extra reminiscence than different member, then it allocate that a lot area

Reminiscence Allocation in Construction and Union

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

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 kind will occupy most area of reminiscence over different knowledge varieties.
Whole reminiscence allocation = 8 Bytes


When use Construction and Union

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

Word:

  1. All of the properties of the construction are identical 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