Skip to main content

Section 15.4 Structures with Functions

You can pass structures as parameters just like any built in data type. For example, printPoint below takes a point as an argument and outputs it in the standard format. If you call printPoint (blank), it will output (3, 4).
void printPoint(Point p) {
  cout << "(" << p.x << ", " << p.y << ")" << endl;
}
That version of the function uses pass by value to make a copy of the point that is passed in. For a very simple struct, we may be willing to pay the price of an unneeded copy. But in general, it is better to use pass by reference to pass structs to avoid that work. And, if the function will not modify the object, we should use pass by const reference. So we will prefer to write functions like this:
void printPoint(const Point& p) {
  cout << "(" << p.x << ", " << p.y << ")" << endl;
}
As a second example, here is a distance that takes two Points as parameters:
Listing 15.4.1.
Similarly, we can return a struct from a function. To do so, we use the struct’s type as the return type. Here is a function that takes a point and returns it’s mirror image over the y-axis:
Listing 15.4.2.

Checkpoint 15.4.1.

What will print?
struct Coordinate {
  int x, y;
};

void printOppositeCoordinate(const Coordinate& p) {
  cout << "(" << -p.y << ", " << -p.x << ")" << endl;
}

int main() {
  Coordinate coord = { 2, 7 };
  printOppositeCoordinate (coord);
}
  • (-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.

Checkpoint 15.4.2.

Construct a function that takes in three Point structures and returns a new point where the x value is the the average of the three points’ x coordinates and the y value is the average of the three points’ y coordinates. Calculate the x average before the y average.
You have attempted of activities on this page.