Pass by Reference vs Pass by Pointer in C++

Posted in /   /   /  

Pass by Reference vs Pass by Pointer in C++
vinaykhatri

Vinay Khatri
Last updated on November 21, 2024

    Pass by reference and pass by pointer are the two popular ways of passing variables to a function in C++. Though they are two different approaches, they yield the same results. So, it is obvious to wonder - which one is better to use, pass by reference or pass by pointer.

    Well, this article will explain the significant differences between pass by reference and pass and pointer methods. Also, it will walk you through a brief overview of pass by reference and pass by pointer with suitable examples.

    However, before diving deep into the topic, we shall first understand what a function is and what are parameters and arguments.

    So, let us get started!

    What is a Function?

    A function in computer programming is a set of instructions that take certain inputs, perform computation, and return the output. The primary objective of a function is to eliminate the need for writing the repetitive code again and again for different inputs in the same program.

    If a specific functionality is present multiple times in a program , instead of writing the same code, again and again, we can create a function and call it in the program wherever required.

    A function runs only when it is called inside a program. It ensures code reusability, i.e., defining a function once and reusing it as many times as you need it in a program. We can pass data to a function known as parameters. While defining a function, we need to specify the number of parameters, the data type of parameters, and the return type of a function.

    Syntax:

    int function1( data_type parameter1, data_type parameter2, …, data_type parameterN)
    
    {
    //code
    return 0;
    }

    Example:

    #include<iostream>
    using namespace std;
    //defining a function 'sum'
    //a and b are parameters
    int sum (int a, int b)
    {
     return a+b;
    }
    int main()
    {
     int num1 = 50, num2 = 40, result;
         //the function 'sum' is called with 
         //num1 and num2 as arguments
     result = sum(num1, num2);
     cout<<"The sum is: "<<result;
     return 0;
    }

    Output:

    The sum is: 90

    From the above example, we understand that arguments are the values that we pass to a function when it is called inside the main program. In our example, num1 and num2 are arguments. Arguments are also called actual parameters.

    On the other hand, parameters are the variables that we define during a function definition or declaration. In our example, a and b are parameters. These parameters receive the arguments passed during a function call, perform computation, and return the results. They are also called formal parameters.

    To pass variables to a function, there are three different ways in C++, namely, pass by value, pass by reference, and pass by pointer. Let us discuss the two ways, namely pass by reference and pass by pointer in detail below.

    pass by reference vs pass by pointer

    What is Pass by Reference?

    Pass by reference implies passing the reference of an argument in the calling function to the corresponding parameters of the called function. Alternatively, pass by reference allows a function to modify the value of a variable without having to create a copy of it.

    In pass by reference, the memory location of the passed variable and parameter is the same, and hence, any changes made to the parameter reflect in the value of the passed variable.

    To pass a variable by reference to a function, we have to declare function parameters as references using the ‘&’ symbol, and not as normal variables. Let us understand pass by reference with one simple example.

    Example:

    #include<iostream>
    using namespace std;
    int display(int& a)
    {
     return a*=3;
    }
    int main()
    {
     int z = 30;
     cout<<"The original value of z is: "<<z;<<endl;
     display(z);
     cout<<"The new value of z is: "<<z<<endl;
     return 0;
    }

    Output:

    The original value of z is: 30
    The new value of z is: 90

    In the above program, we have a basic main function and a display function. In the main function, we have first declared the value of ‘z’ as 30 and printed it. Later, we have called a function ‘display’. The control of the program goes to the function where we have defined it, performs computation, i.e., a*=3, which evaluates to 90, and returns the result.

    Now, the new value of z is 90. Here, ‘int display(int& a)’ becomes our pass reference. In this function, ‘(int& a)’ creates a variable ‘a’ as a copy of ‘z’, referencing its value. The display() function performs the computation on ‘a’ and then replaces the value of ‘z’ with the new value of ‘a’.

    When to Use Pass by Reference?

    You can use pass by reference in C++ for the following three purposes:

    1. Modifying the Local Variables of the Caller Function

    By using pass by reference, we can modify the local variables of the caller function, as we did in the example mentioned above. When you call a function to modify arguments, the only way to do so is pass by reference.

    2. Passing Large-Sized Arguments

    Using pass by reference is beneficial when an argument is significant in size, for example, a string. Pass by reference eliminates the need to move the entire string. In pass by reference, we pass the address of an argument and not the actual argument.

    3. Polymorphism in a Function

    We can make a function polymorphic using pass by reference by passing objects to it.

    What is Pass by Pointer?

    Pass by pointer is another alternative to passing a variable to a function. It implies passing a pointer argument in the calling function to the corresponding parameter of the called function. In other words, pass by reference means passing the memory location of the variables to the parameters in the function and then performing computations.

    Let us implement the pass by pointer method in the following example. Also, we obtained the same results when implemented using pass by reference. Example:

    #include<iostream>
    using namespace std;
    int display(int* a)
    {
     return *a*=3;
    }
    int main()
    {
     int z = 30;
     cout<<"The original value of z is: "<<z<<endl;
     display(&z);
     cout<<"The new value of z is: "<<z<<endl;
     return 0;
    }

    Output:

    The original value of z is: 30
    The new value of z is: 90

    Instead of references, we have used pointers in this example.

    When to Choose Pass by Pointer?

    You can choose pass by pointer when you want to modify the pointer rather than the object the pointer is pointing to.

    Pass by Reference vs Pass by Pointer: Head-to-Head Comparison

    The following table highlights the differences between pass by reference and pass by pointer:

    Pass by Reference Pass by Pointer
    We cannot re-assign a reference. A reference has to be assigned at the initialization. We can reassign a pointer.
    A reference cannot be NULL. A pointer can be NULL.
    We can access the members of a class and structure through references using the ‘.’ operator. We can access the members of a class and structure through pointers using the ‘->’ symbol (arrow symbol).
    A reference always references a variable and shares memory location with it. It is a variable that holds a memory address.
    The value of a variable can be implicitly referenced using the reference name. The dereferencing operator ‘*’ gives the value of a variable.

    Pass by Reference vs Pass by Pointer: Which One Should You Use?

    When we pass a variable to a function either using pass by reference or pass by pointer, we get the same result. The primary difference between pass by reference and pass by pointer is that references refer to the existing variable with a different name, whereas pointers store the address of that variable.

    Consider using the pass by pointer if you want to reassign a pointer or the NULL value is a valid parameter. In addition, if you wish to write C code that compiles on a C and C++ compiler , you have to restrict to pass by pointers. Otherwise, you can go with pass by reference to pass variables to a function.

    Conclusion

    Though pass by reference and pass by pointer approaches serve a similar purpose, they use different ways to accomplish it. The most important thing to remember is that a pointer can be a reference, but vice-versa is not possible. In this article, we have discussed pass by pointer and pass by reference with examples and highlighted the key differences between them.

    We hope that the differences and examples explained in this article have given you enough clarity on pass by reference vs pass by pointer. If you have any queries, you can post them in the comments section below.

    People are also reading:

    FAQs


    The primary difference between pass by reference and pass by pointer is that pointer can be null and reassigned, but references cannot.

    There is actually no need to pass an array by reference explicitly in C++ because an array is always by reference by default.

    You should use pass by reference when you wish to modify the local variables of the caller function, have large-sized arguments, and want to make a function polymorphic.

    Use pass by pointer when you want to actually modify the pointer and not the object the pointer points to.

    Leave a Comment on this Post

    0 Comments