Give the syntax for pass by reference? Compare pass by reference and pass by pointer(address), and conclude which one is preferable and why?
Pass by reference syntax
datatype swap(datatype & x, datatype & y)
Example of pass by reference
#include <iostream>
using namespace std;
void swapNumbers(int& number1, int& number2)
{
int z = number1;
number1 = number2;
number2 = z;
}
int main()
{
int x = 65, y = 90;
cout << "Before Swap\n";
cout << "x = " << x << " y = " << y << "\n";
swapNumbers(x, y);
cout << "After Swap with pass by reference\n";
cout << "x= " << x << " y = " << y << "\n";
}
Differences between pass by reference and pass by pointer
A reference cannot be reassigned once assigned while a pointer can be reassigned
A pass by pointer use * to dereference a pointer while pass by reference
does not require dereferencing and references can be used directly
Pass by reference is preferred over pass by pointer since references cannot be null, thus they are safe.
Comments
Leave a comment