Lecture 04: Structs: Engr. Muhammad Asad Lecturer (EE) Institute of Space Technology, Islamabad Muhammad - Asad@ist - Edu.pk
Lecture 04: Structs: Engr. Muhammad Asad Lecturer (EE) Institute of Space Technology, Islamabad Muhammad - Asad@ist - Edu.pk
Lecturer (EE)
Institute of Space Technology, Islamabad
[email protected]
Struct & Functions
• A function cannot return a value of type array.
• A struct variable can be passed as a parameter either by value or by
reference.
• A function can return a value of type struct.
void printStudent(studentType student)
{
cout << student.firstName << " " << student.lastName
<< " " << student.courseGrade
<< " " << student.testScore
<< " " << student.programmingScore
<< " " << student.GPA << endl;
}
void readIn(studentType& student)
{
int score;
cin >> student.firstName >> student.lastName;
cin >> student.testScore >> student.programmingScore;
cin >> student.GPA;
}
readIn(newStudent);
Arrays vs Structs
Aggregate Operations Arrays Structs
Arithmetic No No
Assignment No Yes
I/Os No No
Comparison No No
Function return Value No Yes
Arrays in Structs
• employeeType employees[50];
Structs within Structs
• To organize information
• Huge structs with lot of members can be broken down to smaller
structs.
• More feasible and understandable.
struct employeeType int hireyear;
{ int quitmonth;
string firstname; int quitday;
string middlename; int quityear;
string lastname; string phone;
string empID; string cellphone;
string address1; string fax;
string address2; string pager;
string city; string email;
string state; string deptID;
string zip; double salary;
int hiremonth; };
int hireday;
• This struct has 22 members.
• Some members of this struct will be accessed more frequently than
others.
• Some members are more closely related than others.
• Moreover, some members will have the same underlying structure.
struct nameType struct dateType
{ {
string first; int month;
string middle; int day;
string last; int year;
}; };
struct addressType struct contactType
{ {
string address1; string phone;
string address2; string cellphone;
string city; string fax;
string state; string pager;
string zip; string email;
}; };
struct employeeType
{
nameType name;
string empID;
addressType address;
dateType hireDate;
dateType quitDate;
contactType contact;
string deptID;
double salary;
};
employeeType newEmployee;
Accessing Members
• newEmployee.name.first = "Mary";
• newEmployee.name.middle = "Beth";
• newEmployee.name.last = "Simmons";