Structures and union

Explain structure.

A structure is a user defined data type, which groups a set of data types. It is a collection of variables of different type under single name. A structure provides a convenience to group of related data types. A structure can contain variables, pointers, other structures, arrays or pointers. A structure is defined with the keyword ‘struct’

Ex:
struct employee
{
int empid;
char name[20];
float salary;
};
..
..
struct employee Catherina;


Structures:

Structures provide a convenient method for handling related group of data of various data types.

Structure definition:

struct tag_name
{
data type member1;
data type member2;


}

Example:
struct library_books
{
char title[20];
char author[15];
int pages;
float price;
};

The keyword struct informs the compiler for holding fields ( title, author, pages and price in the above example). All these are the members of the structure. Each member can be of same or different data type.

The tag name followed by the keyword struct defines the data type of struct. The tag name library_books in the above example is not the variable but can be visualized as template for the structure. The tag name is used to declare struct variables.

Ex: struct library_books book1,book2,book3;

The memory space is not occupied soon after declaring the structure, being it a template. Memory is allocated only at the time of declaring struct variables, like book1 in the above example. The members of the structure are referred as - book1.title, book1.author, book1.pages, book1.price.

Unions

Unions are like structures, in which the individual data types may differ from each other. All the members of the union share the same memory / storage area in the memory. Every member has unique storage area in structures. In this context, unions are utilized to observe the memory space. When all the values need not assign at a time to all members, unions are efficient. Unions are declared by using the keyword union , just like structures.

Ex: union item {
int code;
float price;
};

The members of the unions are referred as - book1.title, book1.author, book1.pages, book1.price.
Properties of Union
Properties of Union - A union is utilized to use same memory space for all different members of union. Union offers a memory section to be treated for one variable type.....
Post your comment