Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

What is the difference between structure and union

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

The post What is the difference between structure and union appeared first on All In One Tuts.



This post first appeared on All In One Tuts | Tech Tutorials And Videos | Tech, please read the originial post: here

Share the post

What is the difference between structure and union

×

Subscribe to All In One Tuts | Tech Tutorials And Videos | Tech

Get updates delivered right to your inbox!

Thank you for your subscription

×