×

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

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

C++ Infinite loop

The term "infinite loop" refers to a loop that does not terminate the loop according to the condition. In some cases, an infinite loop may be required in programming, or...

4 minutes read.

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

Name Mangling and extern in C++

Name Mangling and Function Overloading: Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the...

4 minutes read.

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector: Pass by Value Pass by Reference A copy of a vector...

3 minutes read.

INT_MAX and INT_MIN in C/C++

In competitive programming, assigning a variable that maximum or minimum value a data type can carry is frequently necessary. Still, it might be challenging to recall such a significant, exact...

3 minutes read.

C++ Program to Print Fibonacci Triangle

Fibonacci Triangle Program in CPP Definition: Fibonacci Triangle as the name suggests is the same as the Fibonacci number series where the next element is the sum of the previous two elements....

3 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

C++ Static

What is the Static keyword? In C++, the keyword static is used to give an element some particular properties. Static elements are only given storage in the static storage region once...

4 minutes read.

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.

Functions in C++ with Types and Examples

A function is a collection of statements that work together to complete a certain goal. It could consist of statements that execute repetitive operations or statements that conduct specialized jobs...

10 minutes read.

Inheritance in C++ vs Java

Just like we inherit traits from our parents, object-oriented programming has a concept called inheritance. In terms of object-oriented programming, a class's traits and behaviours, or its data and methods,...

4 minutes read.

std::distance() in C++

The primary function of std::distance is to facilitate the total number of elements if we have two iterators. It is defined inside the header files. It has both magnitude and...

2 minutes read.

Binary Search in C++

The binary search in the C++ programming language will be discussed. By continually halves the array and then seeking specified items from a half array; binary search is a technique...

8 minutes read.

Print Table Using Do while Loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

4 minutes read.

C++ Pointer

Pointer is a derived data type that stores the address of a variable. A pointer is used for memory management and dynamic memory allocation. Pointer works on the address of data rather than...

2 minutes read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

Array of Object in C++

What is an Array? In C++, an array is a group of related data types, such as int, char, float, double, etc., that are easily accessed by index value alone and...

12 minutes read.

C++ String Concatenation

C++ String Concatenation In this section, we will learn about C ++ String Concatenation, what it does, how it works, and will also see its programs. What is the String Concatenation? The + operator...

3 minutes read.