When we want the function to be able to change the value of an argument. When we want to pass a large object as an argument. The time and space costs to copy the object are often too high for real-world applications. When there is no way to copy the object. In these cases we can instead define the parameters as references or pointers 8.4 Reference Parameters As an example of a situation where copying the argument doesn't work, consider a function to swap the values of its two arguments: // incorrect version of swap: The arguments are not changed! void swap(int v1, int v2) { int tmp = v2; v2 = v1; // assigns new value to local copy of the argument v1 = tmp; } // local objects v1 and v2 no longer exist In this case, we want to change the arguments themselves. As defined, though, swap cannot affect those arguments. When it executes, swap exchanges the local copies of its arguments. The arguments passed to swap are unchanged: int main() { int i = 10; int j = 20; cout << "Before swap():\ti: " << i << "\tj: " << j << endl; swap(i, j); cout << "After swap():\ti: " << i << "\tj: " << j << endl; return 0; } Compiling and executing this program results in the following output: Before swap(): i: 10 j: 20 After swap(): i: 10 j: 20 For swap to work as intended and swap the values of its arguments, we need to make the parameters references: // ok: swap acts on references to its arguments void swap(int &v1, int &v2) { int tmp = v2;
When we want the function to be able to change the value of an argument. When we want to pass a large object as an argument. The time and space costs to copy the object are often too high for real-world applications. When there is no way to copy the object. In these cases we can instead define the parameters as references or pointers 8.4 Reference Parameters As an example of a situation where copying the argument doesn't work, consider a function to swap the values of its two arguments: // incorrect version of swap: The arguments are not changed! void swap(int v1, int v2) { int tmp = v2; v2 = v1; // assigns new value to local copy of the argument v1 = tmp; } // local objects v1 and v2 no longer exist In this case, we want to change the arguments themselves. As defined, though, swap cannot affect those arguments. When it executes, swap exchanges the local copies of its arguments. The arguments passed to swap are unchanged: int main() { int i = 10; int j = 20; cout << "Before swap():\ti: " << i << "\tj: " << j << endl; swap(i, j); cout << "After swap():\ti: " << i << "\tj: " << j << endl; return 0; } Compiling and executing this program results in the following output: Before swap(): i: 10 j: 20 After swap(): i: 10 j: 20 For swap to work as intended and swap the values of its arguments, we need to make the parameters references: // ok: swap acts on references to its arguments void swap(int &v1, int &v2) { int tmp = v2;