
Think it through together · A little story
A girl gives a robot two number cards, 3 and 5, and asks it to add them. How does a function get those two cards?
Lay out the process
- Call siteProvides 3 and 5
- Function entryParameters receive values
- CalculationAdd 3 and 5
- ReturnResult: 8
Arguments carry data from the call site into a function.
With pass-by-value, a parameter gets a copy of the value. Imagine copying the numbers onto the function’s own task sheet before doing the calculation.
01What is an argument?
Functions often need data from outside:
int add(int a, int b) {
return a + b;
}
a and b are parameters of this function.
02What is the difference between an argument and a parameter?
int result = add(3, 5);
Arguments
The 3 and 5 provided when the function is called.
Parameters
a and b in the function definition.
03How does C++ pass arguments by default?
Ordinary parameters are passed by value by default.
void change(int x) {
x = 100;
}
int n = 5;
change(n);
After the call, n is still 5.
04Why does changing x inside the function not change n outside?
Because x is a separate parameter object. It gets a copy of the current value of n.
05What if you really want to change the outside variable?
You can use a reference parameter:
void change(int& x) {
x = 100;
}
int n = 5;
change(n);
This time, x refers to n, so assigning to x inside the function changes n.
06How can you read a large object efficiently?
A common approach is to use a const reference:
void printText(const std::string& text) {
std::cout << text;
}
This avoids copying the entire string by value, and the function cannot modify the string through this reference.
07Does a function always need arguments?
No. A function can have no parameters:
void showMenu() {
// ...
}
It can also have several parameters. Their number and types are determined by the function’s interface.
What you have learned
- Values provided when calling a function are arguments; the parameters are the names that receive them in the function definition.
- Ordinary C++ parameters are passed by value by default.
- Pass-by-value gives the function a separate copy, so changing a parameter does not automatically change the argument.
- A reference parameter can refer to an object owned by the caller.
- Const references are often used to read large objects efficiently.
Next: What does return bring back?
Your turn to try
If an integer is passed by value and the function changes only its own parameter, will the original integer change automatically?
Have you thought it through? Open for an explanation
No. The function changes the copy made for that call. To change the caller’s data, you need to explicitly use another approach.