Structures.....cont(1)

Initializing Structure Elements

The elements of a structure van be initialized either seperately using seperate assignment statements or jointly using the notation similar to that used for initializing arrays. The example given below demonstrates how structure elements can be initialized jointly or seperately.

struct student

{

int rollno;

char name[20];

short clas; // class is a reserved word of C++

float marks;

char grade;

} stud1, stud2;

The members of structure stud1 can be initialized seperately as shown below:

stud1.rollno=2;

stud1.name="Rahul";

stud1.clas=12;

stud1.marks=67.00;

stud1.grade='A';

Or, structure members can be initialized jointly thus:

student stud1={2, "Rahul", 12, 67.00, 'A'};

Assigning Structure Variables

One structure variable can be assigned to another.

stud2=stud1;

The above statement assigns each member of stud2 to the corresponding member of stud1.

One structure variable can be assigned to another only if both are of the same type.

Nested Structures

A structure element may be complex or simple. The simple elements of a structure are any of the fundamental data types of C++, ie, int, char, float, double. However, structure may consist of an element that is itself complex, ie, it is made up of fundamental types, eg, arrays, structures etc. Thus an element of a stucture itself may be an array or a structure itself. A structure consisting of such complex elements is called a complex structure.

A structure also can be nested inside another structure. Foe instance:

struct distance //structure tag

{

float feet;

float inches;

};

struct volume

{

distance length;

distance width; // another structure distance present

distance height; // within structure volume

};

volume vol; // create structure variable

Accessing Nested Structure Members

Themembers of structures are accessed using the dot operator. Going back to the example given above, to access the member feet of the stucture length, we can write:

vol.length.feet;

To initialize the member inches of the structure height, we can write as follows:

vol.height.inches=10;

HOME LEARN C++ PREVIOUS NEXT