Passing by pointer Vs Passing by Reference in C++


These are simple example of passing by pointer and passing by reference -

Passing by pointer

 Live Demo

#include <iostream>
using namespace std;
void swap(int* a, int* b) {
   int c = *a;
   *a= *b;
   *b = c;
}
int main() {
   int m = 7, n = 6;
   cout << "Before Swap\n";
   cout << "m = " << m << " n = " << n << "\n";
   swap(&m, &n);
   cout << "After Swap by pass by pointer\n";
   cout << "m = " << m << " n = " << n << "\n";
}

Output

Before Swap
m = 7 n = 6
After Swap by pass by pointer
m = 6 n = 7

Passing by reference

 Live Demo

#include <iostream>
using namespace std;
void swap(int& a, int& b) {
   int c = a;
   a= b;
   b = c;
}
int main() {
   int m =7, n = 6;
   cout << "Before Swap\n";
   cout << "m = " << m << " n = " << n << "\n";
   swap(m, n);
   cout << "After Swap by pass by reference\n";
   cout << "m = " << m << " n = " << n << "\n";
}

Output

Before Swap
m = 7 n = 6
After Swap by pass by reference
m = 6 n = 7

So, if we pass parameter to a function either by pass by pointer or pass by reference it will produce the same result. Only difference is that References are used to refer an existing variable in another name whereas pointers are used to store address of variable. It is safe to use reference because it cannot be NULL.

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements