C PROGRAMMING

Difference between Structure and Union in C

Confused between structure and union, Don’t worry we are here to fend your confusion.

structure vs union

What is structure?

Structure is a user-defined data type, which is a collection of variables of different types under a single name.

Defining structure

To Define a structure in c we have to use the Struct keyword.

Syntax

struct structure_name 
{
    data_type member1;
    data_type member2;
    .
    .
    data_type memeber;
};

What is Union?

The union is a user-defined data type which is used to store different data type in the same memory location.

Syntax

Union Syntax:
union union_name{

member defination;

member defination2;

......

member defination3;

}union variable;

Difference between Structure and Union

Below are the following point for structure

  • Members of structure do not share memory. So A structure needs separate memory space for all its members i.e. all the members have unique storage.
  • Members of structure can be accessed individually at any time.
  • To define Structure, ‘struct’ keyword is used.
  • All members of structure can be initialized.
  • The size of the structure is > to the sum of each member’s size.
  • Change in the value of one member can not affect the other in structure.

Below are the following point for union

  • A union shares the memory space among its members so no need to allocate memory to all the members. Shared memory space is allocated i.e. equivalent to the size of a member having the largest memory.
  • At a time, only one member of union can be accessed.
  • To define Union, ‘union’ keyword is used.
  • Only the first member of Union can be initialized.
  • The size of union is equivalent to the size of the member having largest size.
  • Change in the value of one member can affect the value of other member.

Still confused between structure and union feel free to comment, wer are here to help you.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also
Close
Back to top button