Struct and function
- C++ course
- Beginner
- Lesson 96/116
- 5 min
Learn to pass structs to functions by value and by reference.
Passing a struct to a function
You can pass a struct variable to a function as a parameter. In pass-by-value, the function gets a copy of the struct; the original variable is not changed.
void printPoint(Point p) {
cout << p.x << ", " << p.y;
}Here printPoint takes a Point and prints its members. The call looks like printPoint(p);. Pass-by-value is fine for small structs; for large structs, references are used to avoid the copying cost.
Passing by reference
For large structs, pass-by-reference is used to avoid the copying cost. You add & next to the parameter type; this lets the function see the original struct directly.
void move(Point& p) {
p.x += 1;
p.y += 1;
}Here p is a reference, so p.x += 1 changes the x member of the original struct. If you do not want the struct to change, use const Point&; this avoids copying and protects the data.
Practice Write the printPoint function
Define a function void printPoint(Point p) that prints the members with cout << p.x << " - " << p.y << endl;. In main, declare Point p; p.x = 3; p.y = 4; and call printPoint(p);.
Starter code
#include <iostream>
using namespace std;
struct Point {
int x;
int y;
};
// Define the printPoint function
int main() {
// declare Point p; assign members, call the function
return 0;
}Sample solution
#include <iostream>
using namespace std;
struct Point {
int x;
int y;
};
void printPoint(Point p) {
cout << p.x << " - " << p.y << endl;
}
int main() {
Point p;
p.x = 3;
p.y = 4;
printPoint(p);
return 0;
}Expected output
3 - 4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is used to pass a large struct without copying it?
- reference Correct answer
- derived type
- constant
- pass by value
Explanation: A reference lets you pass the struct without copying.
2 Fill in the blank: reference parameter
void move(Point____ p) {
p.x += 1;
}
void move(Point& p) {
p.x += 1;
}
Explanation: The & marks a reference parameter.
3 Match each passing style with its feature
| Term | Meaning |
|---|---|
by value |
creates a copy |
by reference |
can change the original |
const reference |
no copy, protected |