Monday, October 10, 2022

Pass by Pointer vs Pass by Reference in C++

Variables can be passed by pointer and by reference. Both produce the same result and have the same effect on the arguments passed in the calling function. The difference is that the pointer stores the address to a variable whereas a reference refers to an existing variable in a different name.

Reference: https://www.tutorialspoint.com/passing-by-pointer-vs-passing-by-reference-in-cplusplus

Pass by Pointer:

Code: 
#include <iostream>

using namespace std;

void swapNum(int* a, int* b) {
    int t = *a;
    *a = *b;
    *b = t;
}

int main()
{
    int i = 1;
    int j = 2;
    cout << "Before swapping " << i << " " << j << endl;
    swapNum(&i, &j);
    cout << "After swapping " << i << " " << j << endl;
    return 0;
}
Output:
Before swapping 1 2
After swapping 2 1

Pass by Reference:

Code: 
#include <iostream>

using namespace std;

void swapNum(int& a, int& b) {
    int t = a;
    a = b;
    b = t;
}

int main()
{
    int i = 1;
    int j = 2;
    cout << "Before swapping " << i << " " << j << endl;
    swapNum(i, j);
    cout << "After swapping " << i << " " << j << endl;
    return 0;
} 
Output:
Before swapping 1 2
After swapping 2 1  

No comments:

Post a Comment