Loading lessons...
Passing and Returning Structs
Passing and Returning Structs
A struct flows through your program just like any other value: you pass it into functions and get it back out of them. It lets a function work with all the related data as one unit.
Passing by value (a copy)
#include <iostream>
using namespace std;
struct Car {
string name;
int year;
};
void showCar(Car car) { // receives a whole copy
cout << car.name << " " << car.year << endl;
}
int main() {
Car myCar { "Tesla", 2015 };
showCar(myCar);
return 0;
}
The parameter car gets its own copy of the struct. Changing it inside showCar does nothing to myCar.
Passing by const reference
When a function only reads the struct, the copy is wasted work. A const reference avoids the copy and forbids changes:
void showCar(const Car &car) {
cout << car.name << " " << car.year << endl; // read only
}
constpromises the function will not modify it.&shares the original object instead of copying it.
Passing by reference (to modify)
If the function must change the caller's object, pass a plain reference:
void makeNewer(Car &car) {
car.year = 2025;
}
Changes reach the original car back in the caller.
Returning a struct
A function can build and hand back a whole struct:
Car makeCar(string name, int year) {
return { name, year };
}
Then a call produces a fresh object:
int main() {
Car sedan = makeCar("Honda", 2005); // sedan.name = "Honda", year = 2005
return 0;
}
Which one when
- By value: you want your own copy to do with as you like.
- By const reference: read-only, the default for large structs.
- By reference: the function may modify the original.
- Return the struct when the function builds a new value to hand back.
TL;DR
- Pass by value copies the whole struct:
void f(Car c). - Pass by const reference avoids the copy:
const Car &c. - Pass by reference lets the function modify the original:
Car &c. - Return a struct with
return { name, year };. - Grouping data lets functions work with related values at once.