Mark As Completed Discussion

In programming and particularly in web development, function parameters could be thought of analogously as the 'query parameters' of a URL for an HTTP GET request. They provide an interface to pass information to your function. This makes your function more flexible and reusable. That said, C++ goes further by allowing pass by value and pass by reference.

When passing parameter by value, a copy of the actual argument's value is made into the function's parameter. Modifying the parameter inside this function does not impact anything outside the function. Zero side-effects. This is commonly used when the parameter is of basic data type. To illustrate, below is example code which shows a transfer between two banking accounts using pass-by-value:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4void transfer(int from_account, int to_account, double amount) {
5  from_account -= amount;
6  to_account += amount;
7}
8
9int main() {
10  int account1 = 5000;
11  int account2 = 2000;
12  transfer(account1, account2, 1000);
13  cout << "Account 1: " << account1 << endl;
14  cout << "Account 2: " << account2 << endl;  // Note the account balances remain unchanged
15}

The code shows that pass-by-value will not change the original variables account1 and account2.

Passing by reference, on the other hand, means the actual argument is passed to the function. Changes to the parameter inside the function reflect in the actual argument. It’s as if the original variable (from the calling function’s scope) is used in the called function. This is useful for objects, complex data structures, and when you actually want the called function to modify the caller’s original variables:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4void transfer(int& from_account, int& to_account, double amount) {
5  from_account -= amount;
6  to_account += amount;
7}
8
9int main() {
10  int account1 = 5000;
11  int account2 = 2000;
12  transfer(account1, account2, 1000);
13  cout << "Account 1: " << account1 << endl;  // The account balances are updated now
14  cout << "Account 2: " << account2 << endl;
15}

As seen above, pass-by-reference alters the original variables account1 and account2.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment