⟩ What is C Programming structure?
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.