2078 5

CSC166 ยท 2078 ยท 5 marks

What is meant by pass by reference? How can we pass arguments by reference by using reference variable? Illustrate with example.

What is meant by pass by reference? How can we pass arguments by reference by using reference variable? Illustrate with example. [5]

Object Oriented ProgrammingChapter 2: Basics of C++ programmingFunctions

Quick answer

Pass by reference is a method of passing arguments to a function where the address (location) of a variable is passed to the function. When a function is called by reference, the formal arguments become references to the actual arguments. This means any changes made to the formal parameters inside the function directly affect the actual arguments in the calling function.

Pass by Reference in C++

Definition

In contrast, pass by value sends a copy of the data, so the original variable remains unchanged.


Passing Arguments by Reference Using Reference Variables

In C++, a reference variable is an alias (another name) for an existing variable. It is declared using the & symbol. When used as a function parameter, the formal parameter becomes a reference to the actual argument -- no copy is made, and changes inside the function reflect in the original variable.

Syntax:

return_type function_name(data_type &param1, data_type &param2);

Example: Swapping Two Numbers Using Pass by Reference

#include <iostream>
using namespace std;

// Function using reference variables as parameters
void swap(int &a, int &b) {
    int temp;
    temp = a;
    a = b;
    b = temp;
}

int main() {
    int x = 10, y = 20;

    cout << "Before swap: x = " << x << ", y = " << y << endl;

    swap(x, y);   // x and y are passed by reference

    cout << "After swap:  x = " << x << ", y = " << y << endl;

    return 0;
}

Output:

Before swap: x = 10, y = 20
After swap:  x = 20, y = 10

Explanation

AspectDetail
int &aa is a reference to the actual argument x
int &bb is a reference to the actual argument y
Changes to aDirectly change x in main()
Changes to bDirectly change y in main()
No copy madeMemory efficient; original values are modified

Key Points

  • The & symbol in the parameter list makes the parameter a reference variable.
  • The formal argument and actual argument share the same memory location.
  • No separate copy of the variable is created, unlike pass by value.
  • This is useful when a function needs to modify the original variable or when passing large objects to avoid overhead of copying.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.