References are a great tool to understand how to use. We aren't certain that we will cover them this semester in CSCI 1300, but you will certainly learn them in CSCI 2275. Please consider this reading.

CONTENTS:

Function Parameters: Pass By Reference

In C++, you can pass parameters to functions either by value or by reference. Passing by reference allows you to modify the original variable within the function.

The syntax is:

// pass by reference, note the single `&`
void functionName(<data_type> &parameter_name)
{
    // Function body
}

// pass by value, note the lack of single `&`
void functionName(<data_type> parameter_name)
{
    // Function body
}

Example:

#include <iostream>
using namespace std;

// Function to increment a number by value
void incrementByValue(int num)
{
    num++;
}

// Function to increment a number by reference
void incrementByReference(int &num)
{
    num++;
}

int main()
{
    int x = 5;

    cout << "Before increment: " << x << endl;
    incrementByValue(x); // passing x by value
    cout << "After increment: " << x << endl;

    cout << "---" << endl;

    cout << "Before increment: " << x << endl;
    incrementByReference(x); // passing x by reference
    cout << "After increment: " << x << endl;

    return 0;
}

Before increment: 5

After increment: 5

---

Before increment: 5

After increment: 6

Key points to remember:

  1. Parameters passed by reference are indicated by `&` in the function declaration.
  2. Changes made to the reference parameter within the function affect the original variable.
  3. Pass by reference avoids unnecessary copying of the argument to the parameter variable, which can be more efficient.
  4. Arrays are passed by reference by default (so there is no preceding `&` for an array parameter).
  5. References cannot be reassigned to refer to a different variable once initialized.