by_val by_ref and pointer
by_val
Copy the value from the caller to callee
| classic example | |
|---|---|
return by_val from a function
Return by value means the function returns a new value to the caller. The caller receives its own object, so changing it does not change the local variable that was inside the function.
| return by value | |
|---|---|
Output:
In this example, x is a local variable inside make_number.
After the function returns, x is gone, but its value was used to initialize
a in main.
ref
A reference is another name (alias) for an existing variable.
It does not create a new int; it points to the same object.
| reference | |
|---|---|
Output:
r and a are two names for the same value.
Changing r changes a.
by_ref
Pass by reference means the function parameter is a reference to the caller variable. The function can modify the original variable.
| pass by reference | |
|---|---|
Output:
In void increment(int& x), x is not a copy.
It is a reference to a, so x++ changes a.
return by_ref from a function
Return by reference means the function returns a reference to an existing object. The caller can use the returned value to modify that original object.
| return by reference | |
|---|---|
Output:
first_item(numbers) returns a reference to numbers[0].
Because the return type is int&, assigning to the function result changes the
array element itself.
Do not return a reference to a local variable: