8.5. Structures as parametersΒΆ
You can pass structures as parameters in the usual way. For example,
void printPoint (Point p) {
cout << "(" << p.x << ", " << p.y << ")" << endl;
}
printPoint
takes a point as an argument and outputs it in the
standard format. If you call printPoint (blank)
, it will output
(3, 4)
.
The active code below uses the printPoint
function. Run the code to
see the output!
As a second example, we can rewrite the distance
function from
Section 5.2 so that it takes two Point
s as
parameters instead of four double
s.
double distance (Point p1, Point p2) {
double dx = p2.x  p1.x;
double dy = p2.y  p1.y;
return sqrt (dx*dx + dy*dy);
}
The active code below uses the updated version of the distance
function.
Feel free to modify the code!
(2, 7)

Take a close look at the printOppositeCoordinate function.
(2.0, 7.0)

Take a close look at the printOppositeCoordinate function.
(7, 2)

Yes, this is the correct output.
(7.0, 2.0)

Take a close look at the Coordinate struct.
Q3: What will print?
struct Coordinate {
int x, y;
};
void printOppositeCoordinate (Coordinate p) {
cout << "(" << p.y << ", " << p.x << ")" << endl;
}
int main() {
Coordinate coord = { 2, 7 };
printOppositeCoordinate (coord);
}
Construct a function that takes in three Point structures and prints the average of the x coordinates and the average of the y coordinates as a coordinate. Find the x average before the y average.