
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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.
- Related Questions & Answers
- Are there benefits of passing by pointer over passing by reference in C++?
- PHP Passing by Reference
- Fetch domain name by passing name in MySQL?
- Pass by reference vs Pass by Value in java
- Why do we pass a Pointer by Reference in C++?
- Pass by reference vs value in Python
- C++ Program to Multiply two Matrices by Passing Matrix to Function
- C++ Program to Add Complex Numbers by Passing Structure to a Function
- What MySQL CONCAT() function returns by passing the numeric arguments?
- Message Passing vs Shared Memory Process communication Models
- Passing the Assignment in C++
- Parameter Passing Techniques in C/C++
- How to delete an element from the Set by passing its value in C++
- Passing arrays to methods in C#?
- Passing Arrays to Function in C++
Advertisements