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. (See SectionΒ 10.2 to review references and pass by reference.)
And, if the function will not modify the struct, 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;
}
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 a new Point representing its mirror image over the y-axis:
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. You will not need all of the blocks.
You have attempted of activities on this page.
