We have used the declaration of nested structures on the parent structure in the same declaration. The structures may also be declared separately and included in the parent structure. The innermost structure should be declared first, then the next enveloping structure and then the next enveloping structure. The code is illustrated in Program.
Three structures are declared: The first is Bonus, which has one data member x; the second is Salary, which has two members (one basic pay and other an instance of Bonus); the third is the struct Employee, which has three members namely Name, Age, and Salary. The important thing is how the structure Employee is initialized. In one case, i.e., El, all the data is given like array type initialization; that is, the data values are put in curly brackets and are separated with commas. In case of E2, each data is assigned separately. The following two codes should be understood. In case of Basic_pay there are two selections, (E2.pay.Basic_pay) and in case of x there are three selections (E2.pay.Bon.x).
Illustrates use of typedef with nested structures
# include <stdio.h> typedef struct { int x; } Bonus; typedef struct { int Basic_pay; Bonus Bon; } Salary; typedef struct { char* Name; int Age; Salary pay; } Employee; void main () { Employee E2; Employee E1= {"Dinesh", 45, 12000, 2000}; clrscr(); E2.pay.Basic_pay = 14000; E2.pay.Bon.x = 3000; E2.Age = 25; E2.Name = "Shubhra"; printf(" Name \tAge\tBasic pay\tBonus\n"); printf ( "%s\t%d\t%d\t\t%d\n", E1.Name, E1.Age, E1.pay.Basic_pay, E1.pay.Bon); printf( "%s\t%d\t%d\t\t%d\n", E2.Name, E2.Age, E2.pay.Basic_pay, E2.pay.Bon); }