Passing by Pointer

Here, the memory location (address) of the variables is passed to the parameters in the function, and then the operations are performed. It is also called the call by pointer method.

C++




// C++ program to swap two numbers using
// pass by pointer
#include <iostream>
using namespace std;
 
void swap(int *x, int *y)
{
    int z = *x;
    *x = *y;
    *y = z;
}
 
// Driver Code
int main()
{
    int a = 45, b = 35;
    cout << "Before Swap\n";
    cout << "a = " << a << " b = " << b << "\n";
 
    swap(&a, &b);
 
    cout << "After Swap with pass by pointer\n";
    cout << "a = " << a << " b = " << b << "\n";
}


Output

Before Swap
a = 45 b = 35
After Swap with pass by pointer
a = 35 b = 45

Passing By Pointer vs Passing By Reference in C++

In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++?

Let’s first understand what Passing by Pointer and Passing by Reference in C++ mean:

Similar Reads

Passing by Pointer

Here, the memory location (address) of the variables is passed to the parameters in the function, and then the operations are performed. It is also called the call by pointer method....

Passing By Reference

...

Pass by Pointer vs Pass by Reference

It allows a function to modify a variable without having to create a copy of it. We have to declare reference variables. The memory location of the passed variable and parameter is the same and therefore, any change to the parameter reflects in the variable as well....

Difference Between Reference Variable and Pointer Variable

...

Which is preferred, Passing by Pointer Vs Passing by Reference in C++?

The following table lists the major differences between the pass-by-pointer and pass-by-reference methods....

Contact Us