×

C++ Call by Reference

Call by Reference is a C++ method for passing arguments to a function that enables us to pass the actual memory address of the parameter rather than a copy of its value. The function can now directly change the initial variable due to it.

Working:

  • The function argument is referenced by the & (ampersand) symbol.
  • The parameter itself is affected by internal modifications made to the function.
  • By eliminating unnecessary duplication of large objects, performance is enhanced.

Key Features:

Several key features of the call by reference in C++ are as follows:

The initial variable is modified:

  • Any changes made inside the function have an effect outside of it because it interacts directly with the original variable.

Uses Memory Addresses:

  • Instead of passing a copy, the original variable is referenced in order to save memory.

Optimized for Big Data Types:

  • As it avoids unnecessary repetition, it is ideal for passing large structures, arrays, and objects.

The Use of Ampersands (&) in Syntax:

  • In the function specification, parameters are provided with & to display references.
  • Example: void func(int &x) { x = x * 2; }

Increased Action Speed:

  • Because no copies are created, function calls execute faster, which improves performance.

Capable of Identifying Different Values:

  • Functions can alter more than one variable by supplying multiple references.

Example 1:

Let us take an example to illustrate the Call by Reference in C++.

#include <iostream>

using namespace std;

// Function using Call by Reference

void modifyValue(int &x) {

    x = x * 2; // Modifying the original variable

}

int main() {

    int num = 10;

    cout << "Before function call: " << num << endl;   

    modifyValue(num); // Passing by reference   

    cout << "After function call: " << num << endl;

    return 0;

}

Output:

Before function call: 10

After function call: 20

Algorithm:

  • Start
  • Declare a function that takes a reference parameter.
  • Inside the function, modify the referenced variable.
  • In the main function:
1. Declare a variable and initialize it.

2. Print its value before the function call.

3. Call the function and pass the variable by reference.

4. Print the value after the function call.
  • End

Pseudo code:

BEGIN

    DEFINE FUNCTION ModifyValue(REFERENCE x)

        x ← x * 2  // Modify the original variable

    END FUNCTION


    MAIN

        DECLARE num ← 10

        PRINT "Before function call: ", num

       

        CALL ModifyValue(num)  // Passing by reference

       

        PRINT "After function call: ", num

    END MAIN

END

Advantages:

  • Changes Original Value: Changes persist once the function is completed.
  • Efficient Memory Utilization: No new copies are created.
  • Advantageous for Big Data Structures: It reduces unnecessary overhead when copying objects.

Example 2:

Let us take a C++ example code for Swapping of Two Numbers by using Call by Reference:

#include <iostream>

using namespace std;

// Function to swap two numbers using Call by Reference

void swapNumbers(int &a, int &b) {

    int temp = a;

    a = b;

    b = temp;

}

int main() {

    int num1 = 5, num2 = 10;   

    cout << "Before swapping: " << endl;

    cout << "num1 = " << num1 << ", num2 = " << num2 << endl;   

    swapNumbers(num1, num2); // Passing by reference   

    cout << "After swapping: " << endl;

    cout << "num1 = " << num1 << ", num2 = " << num2 << endl;   

    return 0;

}

Output:

Before swapping:

num1 = 5, num2 = 10

After swapping:

num1 = 10, num2 = 5

Explanation:

The function swapNumbers(int &a, int &b):

  • It receives two integer references as parameters they are &a and &b.
  • It swaps their values using a temporary variable.

Main Function:

  • Numer1 is set to 5 and Numer2 to 10.
  • Calling swapNumbers(num1, num2) instantly modifies num1 and num2.
  • The values that have been changed are printed.

Example 3:

Let us take a C++ example to find the square of a number by using the call by reference:

#include <iostream>

using namespace std;

// Function to calculate the square using Call by Reference

void findSquare(int &num) {

    num = num * num; // Modifies the original variable

}

int main() {

    int value = 6;   

    cout << "Before function call: " << value << endl;   

    findSquare(value); // Passing by reference   

    cout << "After function call (Square): " << value << endl;   

    return 0;

}

Output:

Before function call: 6

After function call (Square): 36

Conclusion:

In C++, calling by reference is a more efficient way to supply parameters to functions by giving the variable's real memory address rather than making a copy. For situations like value swapping, altering large data structures, and producing multiple outputs, it enables functions to directly change the original variable. Call by Reference increases program efficiency, particularly when working with large objects, by reducing execution time and removing the need for additional memory allocation. It needs to be used carefully to prevent inadvertent changes to variables. Overall, Call by Reference is a strong feature that offers alternatives for function design in addition to performance advantages.


Related Topics

Call by Pointer in C++

What is Pointer? Every variable in C++ has a specific address or location in the computer's memory, and this address is known as the memory address. A pointer can be defined...

5 minutes read.

Computing index using Pointers Returned by STL Functions in C++

In this tutorial we will learn how to compute index using pointers which returned by STL functions in C++. Many built-in C++ functions return pointers to memory places that provide...

2 minutes read.

fscanf() Function in the C++

In the C++ programming language, the fscanf() method can be used to read data from a file stream. Syntax: The syntax for the fscanf() function in the C++ programming language is as...

3 minutes read.

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

8 minutes read.

Sliding Window Technique in C++

Sliding Window Technique or Window Sliding Technique is a computational technique that is mainly used to reduce the use of nested loop and replace it with a single loop. It...

4 minutes read.

Armstrong Number Program in C++

Let's first define Armstrong number before writing the C++ program to check whether the number is Armstrong or not. The sum of the cubes of its digits is equal to the...

2 minutes read.

C++ Fibonacci Series

What is a Fibonacci series? A Fibonacci series or sequence is a very popular programming paradigm. The next element occurring in the N terms series is determined by the sum of...

2 minutes read.

What does Buffer Flush mean in C++

A buffer flush, to explain simple layman's terms, is nothing but the transfer of computer data which is being stored in a rentable temporary memory of your computer running either...

3 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 minutes read.

Constructor Overloading

The program contains more than one constructor in a class with the same name, and different types of arguments are called constructor overloading. Calling of constructor depends on the number and types...

2 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

Depth First Search Program to Traverse a Graph in C++

Depth First Search (DFS) is a technique that is used for transversing the graph. The process of Depth First Search (DFS) starts from the root node and then next comes...

6 minutes read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.

Structured Binding in C++

Structured binding is the new feature of C++ 17. It is used to bind the specified name with an element of the initializer. Structure binding is used to declare multiple...

3 minutes read.

C++ Pipe Tutorial

A pipe is a mechanism for inter-process communication (IPC) in a Unix-like operating system. It allows two or more processes to communicate with each other by sending and receiving data...

3 minutes read.

How to Use Getline in C++

What is getline in C++? Similar to the cin function, which allows the programmer to take input from the user getline() function also takes input from the user. But in this...

4 minutes read.

C++ Global Variable

In C++, a global variable is a variable that is defined outside of any function or class and can be accessed by any function or class in the program. Global...

4 minutes read.

C++ Convert Int to String

In fact, the conversion of numbers to strings or vice versa represents a significant paradigm change. We often need to convert a number to a string or a string to...

2 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.