Programming
c++ pointers reference parameter-passing
Updated Fri, 22 Jul 2022 03:59:40 GMT

Pass by pointer & Pass by reference


Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
Are there benefits of passing by pointer over passing by reference in C++?

In both cases, I achieved the result. So when is one preferred over the other? What are the reasons we use one over the other?

#include <iostream>
using namespace std;
void swap(int* x, int* y)
{
    int z = *x;
    *x=*y;
    *y=z;
}
void swap(int& x, int& y)
{
    int z = x;
    x=y;
    y=z;
}
int main()
{
    int a = 45;
    int b = 35;
    cout<<"Before Swap\n";
    cout<<"a="<<a<<" b="<<b<<"\n";
    swap(&a,&b);
    cout<<"After Swap with pass by pointer\n";
    cout<<"a="<<a<<" b="<<b<<"\n";
    swap(a,b);
    cout<<"After Swap with pass by reference\n";
    cout<<"a="<<a<<" b="<<b<<"\n";
}

Output

Before Swap
a=45 b=35
After Swap with pass by pointer
a=35 b=45
After Swap with pass by reference
a=45 b=35



Solution

A reference is semantically the following:

T& <=> *(T * const)

const T& <=> *(T const * const)

T&& <=> [no C equivalent] (C++11)

As with other answers, the following from the C++ FAQ is the one-line answer: references when possible, pointers when needed.

An advantage over pointers is that you need explicit casting in order to pass NULL. It's still possible, though. Of the compilers I've tested, none emit a warning for the following:

int* p() {
    return 0;
}
void x(int& y) {
  y = 1;
}
int main() {
   x(*p());
}




Comments (5)

  • +1 – References don't restrict the referring object to referring to something valid. You can return a reference to a local variable, for example. — Dec 20, 2011 at 05:22  
  • +1 – It is possible to get a an invalid reference if you dereference a NULL pointer, so you still need to be careful in the calling code. See stackoverflow.com/questions/57483/… — Dec 20, 2011 at 05:22  
  • +1 – It's possible, but unless you're dereferencing unchecked pointers, then it shouldn't happen. And if you don't check pointers before dereferencing them, then I have news for you... — Dec 20, 2011 at 05:24  
  • +0 – @moshbear, it was a lesson I had to learn the hard way. And it wasn't even my code! — Dec 20, 2011 at 05:32  
  • +0 – I simplified my answer and gave an example of the infamous null reference. — Dec 20, 2011 at 05:38