• Home
  • 6.10 Passing by Reference

6.10 Passing by Reference

View Categories

6.10 Passing by Reference

< 1 min read

Table of Contents

Passing by reference allows a function parameter to refer directly to an object supplied by the caller. Unlike passing by value, no separate copy of the argument is created. Changes made through the reference therefore affect the original variable.

A reference parameter is declared by placing & after the parameter’s type. This mechanism is commonly used when a function needs to modify the caller’s object or when copying a large object should be avoided.

Source Code #

#include <iostream>

void updateValue(int& value)
{
    value = 100;
}

int main()
{
    int number = 50;

    updateValue(number);

    std::cout << "Number: " << number << '\n';

    return 0;
}

Output #

Number: 100

Explanation #

  • int& value declares value as a reference parameter.
  • updateValue(number) passes the variable number to the function.
  • The reference parameter value refers directly to the original number object.
  • value = 100; therefore modifies the original variable rather than a copy.
  • After updateValue() returns, number contains 100.
  • Passing by reference allows a function to modify an object supplied by the caller.
  • A reference parameter must be initialized with a valid object when the function is called.
  • Passing by reference can also avoid copying large objects, which can improve efficiency.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *