Answer to Question #236109 in C++ for SOM

Question #236109

Give the syntax for pass by reference? Compare pass by reference and pass by pointer(address), and conclude which one is preferable and why?


1
Expert's answer
2021-09-16T13:02:57-0400

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.


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS