The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

Structures as Return Types

You can write functions that return structures. For example, findCenter takes a Rectangle as an argument and returns a Point that contains the coordinates of the center of the Rectangle:

Point findCenter (Rectangle& box)
  double x = box.corner.x + box.width/2;
  double y = box.corner.y + box.height/2;
  Point result = {x, y};
  return result;

To call this function, we have to pass a box as an argument (notice that it is being passed by reference), and assign the return value to a Point variable:

  Rectangle box = { {0.0, 0.0}, 100, 200 };
  Point center = findCenter (box);
  printPoint (center);

The output of this program is (50, 100).

Last Update: 2005-12-05