c++ use pointers or references code example
Example 1: difference between pointer and reference
//Passing by Pointer://
// C++ program to swap two numbers using
// pass by pointer.
#include
using namespace std;
void swap(int* x, int* y)
{
int z = *x;
*x = *y;
*y = z;
}
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";
}
o/p:
Before Swap
a = 45 b = 35
After Swap with pass by pointer
a = 35 b = 45
//Passing by Reference://
// C++ program to swap two numbers using
// pass by reference.
#include
using namespace std;
void swap(int& x, int& y)
{
int z = x;
x = y;
y = z;
}
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 reference\n";
cout << "a = " << a << " b = " << b << "\n";
}
o/p:
Before Swap
a = 45 b = 35
After Swap with pass by reference
a = 35 b = 45
//Difference in Reference variable and pointer variable//
References are generally implemented using pointers. A reference is same object, just with a different name and reference must refer to an object. Since references can’t be NULL, they are safer to use.
A pointer can be re-assigned while reference cannot, and must be assigned at initialization only.
Pointer can be assigned NULL directly, whereas reference cannot.
Pointers can iterate over an array, we can use ++ to go to the next item that a pointer is pointing to.
A pointer is a variable that holds a memory address. A reference has the same memory address as the item it references.
A pointer to a class/struct uses ‘->'(arrow operator) to access it’s members whereas a reference uses a ‘.'(dot operator)
A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly.
Example 2: calling by reference and pointers c++
#include
using namespace std;
// Function prototype
void swap(int&, int&);
int main()
{
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(a, b);
cout << "\nAfter swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
void swap(int& n1, int& n2) {
int temp;
temp = n1;
n1 = n2;
n2 = temp;
}
Example 3: calling by reference and pointers c++
#include
using namespace std;
// Function prototype
void swap(int*, int*);
int main()
{
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(&a, &b);
cout << "\nAfter swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
void swap(int* n1, int* n2) {
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}