- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Passing by pointer Vs Passing by Reference in C++
These are simple example of passing by pointer and passing by reference -
Passing by pointer
#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
#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.
Advertisements