Passing by Reference Vs. Passing by the pointer in C++
Passing by Reference Vs. Passing by the pointer in C++
Throughout C++, it can transfer parameter values except by pointers or through referring to a function. For both cases, we have the same result. So the remaining statements are inevitable; when one is over the other significant? What are the causes we’re using one over another?
Passing by Pointer:
// C++ program for swaping two numbers with pass-by-pointer. #include <iostream> using namespace std; void swap(int* t, int* p) { int k = *t; *t = *p; *p = k; } int main() { int s = 78, c = 55; cout << "Before Swap\n"; cout << "s = " << s << " c = " << c << "\n"; swap(&s, &c); cout << "After Swap with pass by pointer\n"; cout << "s = " << s << " c = " << c << "\n"; }
Output:
Passing by Reference:
// C++ program to swap two numbers using // pass by reference. #include <iostream> using namespace std; void swap(int& w, int& q) { int l = w; w = q; q = l; } int main() { int n = 122, m = 210; cout << "Before Swap\n"; cout << "n = " << n << " m = " << m << "\n"; swap(n, m); cout << "After Swap with pass by reference\n"; cout << "n = " << n << " m = " << m << "\n"; }
Output:
The difference in between Reference variable and pointer variable
- Generally, references are applied with pointers. A reference is the same object; it only has to refer to an entity with a different name and context. They are safer to use as references cannot be NULL.
- A pointer may be reassigned while the relation cannot be assigned and must only be allocated at initialization.
- The pointer is explicitly assignable to NULL, while reference cannot.
- Pointers may append over an array, and we can use + + to move towards the next object a pointer points toward.
- The variable is a way that has an address to the memory. A reference has the same address as the object it is referring to.
- A class or struct pointer requires' ->'(arrow operator) to reach its members while a reference uses a. '(dot operator)
- To access the memory location it refers to, a pointer must be dereferenced with *, while a pointer can be substituted directly.
// C++ program to display variations between reference and pointer. #include <iostream> using namespace std; struct demo { int s; }; int main() { int m = 3; int n = 8; demo d; int *k; k = &m; k = &n; // 1. Pointer reintialization allowed int &t = m; // &r = y; // 1. Compile Error t = n; // 1. m value becomes 3 k = NULL; // &r = NULL; // 2. Compile Error k++; // 3. Points to next memory location t++; // 3. m values becomes 8 cout << &k << " " << &m << endl; // 4. Different address cout << &t << " " << &m << endl; // 4. Same address demo *q = &d; demo &qq = d; q->s = 9; // q.s = 9; // 5. Compile Error qq.s = 9; // qq->s = 9; // 5. Compile Error cout << k << endl; cout << t << endl; return 0; }
Output: