< previous page page_777 next page >

Page 777
The expression student.lastName[0] would access the first letter in the last name, student.firstName[1] would access the second letter in the first name, and so on.
In addition to accessing individual components of a struct variable, we can in some cases manipulate structs as a whole. C++ is more permissive about aggregate operations on structs than on arrays, but there still are restrictions. The following table compares arrays and structs with respect to aggregate operations:
Aggregate OperationArraysStructs
I/ONo (except strings)No
AssignmentNoNo
ArithmeticNoNo
ComparisonNoNo
Parameter passageBy reference onlyBy value or by reference
Return as a function's return valueNoYes

According to the table, one struct variable can be assigned to another. However, both variables must be declared to be of the same type. For example, if student and anotherStudent are both declared to be of type StudentRec, the statement
anotherStudent = student;
copies the entire contents of the struct variable student to the variable anotherStudent, member by member.
An entire struct can also be passed as a parameter, either by value or by reference, and a struct can be returned as the value of a value-returning function. Let's define a function that takes a StudentRec variable as a parameter.
The task of this function is to determine if a student's grade in a course is consistent with his or her overall grade point average (GPA). We define consistent to mean that the course grade is the same as the rounded GPA. The GPA is calculated on a 4-point scale, where A is 4, B is 3, C is 2, D is 1, and F is 0. If the rounded GPA is 4 and the course grade is A, then the function returns TRUE. If the rounded GPA is 4 and the course grade is not A, then the function returns FALSE. Each of the other grades is tested in the same way.
The Consistent function is coded below. The formal parameter aStudent, a struct of type StudentRec, is passed by value. (Assume that the data type Boolean has been defined previously.)

 
< previous page page_777 next page >