Nesting Of Structures

A small warning. Many of my classmates started to have all their problems from nesting of structures. It may be a bit confusing but once you understand it, it’s very easy. Even if you feel you can’t understand it now, just skip this part. It’s not a must to know nesting.
Anyway I shall try and make it as lucid and simple as possible. Before I jump into the program let me give you a little insight into the problem that we face and why we need to go for nesting.
Consider your room. Every room has its own length and width. At the same time, if you are measuring all your distances in feet and inches then, length has feet as well as inches. Similarly width will also have feet and inches.

From the above diagram it can be seen that feet and inches are common to length and width. Hence feet and inches can be grouped under the structure distance.
Length and width are common for each room. Hence they are grouped under the structure room.
Now, feet and inches come under distance. Hence length can be declared as distance length; which means length has the data type of distance. Distance is a class with feet and inches. Therefore, length will also have feet and inches.

// To
calculate the area of a dining room in square feet
struct
distance // INNER
STRUCTURE
{
int feet;
float
inches;
};
struct room
{
distance
length;
distance
width;
};
int
main ( )
{
room
dining; //
DINING IS A ROOM
dining.length.feet
= 13; //
INITIALISING EACH ELEMENT
dining.length.inches
= 6.5;
dining.width.feet
= 10;
dining.width.inches
= 0.0;
float len =
dining.length.feet + (dining.length.inches/12) ; // CONVERTING INCHES TO FEET
float w
= dining.width.feet + (dining.width.inches/12) ;
cout<<
“The area of the dining room is ”<< len*w << “square feet”
return 0;
}

In the above example distance is the inner structure.
In the expression dining.length.feet : dining
is name of the variable, length is member of the structure and feet is member
of the inner structure.
The four values of length and feet
for dining can also be initialized as follows :
room dining
= {{13,6.5},{10,0.0}};
This is also acceptable.

In the next section we deal with : Enumerated Data Types
or go
back to Contents

Copyright © 2002 Sethu Subramanian All rights reserved.