Structure And Union

Structure 

A structure is a collection of variables under a single name. These variables can be of different types, and each has a name which is used to select it from the structure. A structure is a convenient way of grouping several pieces of related information together.

A structure is combination of different data types. Structs are generally useful whenever a lot of data needs to be grouped together--for instance, they can be used to hold records from a database or to store information about contacts in an address book. In the contacts example, a struct could be used that would hold all of the information about a single contact--name, address, phone number, and so forth.

Syntax: struct Tag { Members }; struct Tag name_of_single_structure;

main() { name_of_single_structure.name_of_variable; }

Example:

struct emp{ int id_number; int age; float salary; };

int main() { emp employee; //There is now an employee variable that has modifiable // variables inside it. employee.age = 22; employee.id_number = 1; employee.salary = 12000.21; }

Union 

A union is an object similar to a structure except that all of its members start at the same location in memory. A union can contain the value of only one of its members at a time. The default initializer for a union with static storage is the default for the first component; a union with automatic storage has none.

#include #include

union {   char birthday[9];   int age;   float weight; } people;

int main(void) {   strcpy(people.birthday, "03/06/56");   printf("%sn", people.birthday);   people.age = 38;   printf("%sn", people.birthday); }

Output : 03/06/56 &

Post Comment
Login to post comments