Structure: Structure Variable in Assignment Statements, Structure within Structure and Initializing Nested Structure

Get unlimited access to the best preparation resource for IAS/Mains/Optional Public-Administration: Get detailed illustrated notes covering entire syllabus: point-by-point for high retention.

Download PDF of This Page (Size: 168K)

Image of Datatype

Image of Datatype

Diagram shows data types

Diagram Shows Data Types

Structure

Structure Variable in Assignment Statements

The statement

S3 = S2.

  • assigns the value of each member of S2 to the corresponding member of S3.

  • Since a large structure can have many members, such an assignment statement requires the compiler to do a considerable amount of work.

  • Note that one structure variable can be assigned to another only when they are of the same structure type, otherwise compiler will give an error.

Structure Within Structure

This is called nesting of structure. Consider the following program in which date field is a structure.

# include < iostream.h >

# include < stdio.h >

struct today

{

int month.

int date.

int year.

};

struct biodata

{

char name [ 20].

today date _of_ birth.

char add [30].

};

void main ()

{

biodata b.

cout << “Enter name”.

gets (b.name).

cout << “Enter birth month”.

cin >> b. date _of _birth. month.

cout << “Enter birth date”.

cin >> b. date _of _birth. date.

cout << “Enter birth year”.

cin >> b. date _of _birth. year.

cout << “Enter address”.

gets (b. adds).

cout << “Name” << b.name << “\n”.

cout << “Month” <<b. date _of_ birth. month << “\n”;

cout << “Date” << b. date _of_ birth. date << “\n”.

cout << “Year” << b. date _of _birth. year << “\n”.

cout << “Address” << b. adds << “\n”.

}

Accessing Nested Structure Members

As the structure is nested inside another, we must apply the dot operator twice to access the structure members:

cin >> b. date_ of_ birth. month.

Initializing Nested Structure

It is initialized at the time of declaration of structure variable.

For example:

biodata bd = {“MOHIT”, {3, 21, 1991}, “Rohini”}.

The inner braces are required just to separate the values, although it is ignored by the compiler.

Developed by: