Sometimes changing the caller's value is the purpose of a function. A restocking helper should update the existing count, not merely calculate a private replacement and discard it. A writable reference parameter makes that change possible.
#include <iostream>
void addGuests(int& count, int arriving) {
count += arriving;
}
int main() {
int guests = 4;
addGuests(guests, 3);
std::cout << guests << '\n';
}
The program prints 7. count is another name for guests during the call. The parameter arriving is still passed by value, because the helper only reads that small integer. void says that no return value is produced; the visible result is the updated argument.
Compare three parameter forms: int count creates a copy, int& count permits updating the caller, and const int& count reads through a reference without permitting that update. For small read-only numbers, passing by value is usually the simplest choice. Choose a writable reference only when the function's job really includes mutation.
At the call site, pass the variable normally. It must be a writable object for this int& parameter; do not pass a number literal and expect the function to change it. The function name and explanation should also make the update clear to the reader.
The starter already declares units as a writable reference. Add the update inside the empty restock body, using delivered as the amount to add. There is no returned result to assign in main: when each call finishes, its original variable has already changed. Check both the pens and pads lines to see the same helper update two different objects.
restock, add delivered to the referenced units. The supplied calls should print Pens: 9 and Pads: 8.Edit main.cpp, then select Run to inspect the Console. Select Submit to check your completed tasks.