Difference between Structure and Union | Allinonetuts

Difference between Structure and Union

Structures and Unions:

A structure is a collection of dissimilar data types. A structure may be defined in terms of its individual members. In general terms, the composition of a structure may be defined as

struct tag
{    
member 1;
member 2;
member n;
};

In this declaration, a struct is a required keyword; the tag is a name that identifies structures of this type (i.e, structures having this composition); and member 1, member 2 ……      member m are individual member declaration. The individual members can be ordinary variables, pointers, arrays or other structures.

Read This: To Check More C Programming Tutorials.

Example :

struct account 
{ 
int acct_no;
char acct_type;
char name [80];
float balance;
};

This structure is named account. It contains four members an integer quantity (acct no), a single character (acct_type), and 80-element character array (name [80]) and a floating point quantity (balance).

Unions :

Unions, like structures, contain members whose individual data types may differ from one another. However, the members within a union all share the same storage area within the computer’s memory, whereas each member within a structure is assigned its own unique storage area. Like structure, a union can be declared using keyword union like

Union Item
{
int m;
float x;
char c;
code;
}

Union is best, because, a union creates a storage location that can be used by any one of its members at a time. When a different member is assigned a new value, the new value suppressed the previous member’s value. So, unions may be used in all places, where a structure is not allowed.

The above example declares a variable code of Union item. The union contains three members, each with different data type. However, we can use only one of them at a time.

This is due to the fact that only one location is allocated for a union variable, irrespective of its size.

Difference between Structure and Union | Allinonetuts

Hello Viewers,
welcome to the Allinonetuts a Technical tutorial and Programming Blog Maintained by Vikas Kardam, a Web Developer and Blogger From Delhi, India.
What is the difference between structure and union was last modified: July 1st, 2017 by Vikas Kardam
Submit your review
1
2
3
4
5
Submit
     
Cancel

Create your own review

Average rating:  
 1 reviews

Nice article

Leave a Reply

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