Loading lessons...
Passing Structs to Functions
Passing Structs to Functions
A struct groups several variables into one bigger object. Passing that struct into a function works like passing anything else.
Define and pass by value
Define the struct type, then use it as a parameter type:
struct Person {
string name;
int age;
};
void greet(Person p) {
cout << p.name << " is " << p.age;
}
Person pis the parameter: a local copy of the struct.- Inside you use the dot to reach members:
p.name,p.age. - Passing by value copies the entire struct, including all members.
The const reference improvement
Structs can be big, and copying all those fields costs time. For a function that only reads, pass a const reference:
void greet(const Person &p) {
cout << p.name << " is " << p.age;
}
const Person &reads "const reference to Person".- No copy is made (cheap for large structs) and
constblocks accidental changes. - Fast and safe at the same time.
When to choose which
- By value: small structs, or when you want your own copy to modify.
- By const reference: big structs that are read-only - the common default.
- By non-const reference: the function must modify the original struct.
TL;DR
- A struct parameter is declared like any other:
void f(Person p). - Reach members with the dot operator:
p.name. - Pass by value copies the whole struct.
- For read-only access to big structs, pass by const reference.
- Use a non-const reference when the function may modify the original.