1

Both of these functions rewrites the original value right? Is there any benefit to doing it one way over the other?

#include <iostream>
using namespace std;

void passptr(int *p)
{
    *p = 7;
}

void passaddy(int &a)
{
    a = 7;
}

int main()
{
    int a = 5;
    int *p = &a;

    passptr(p);
    cout << a << endl;

    a = 5;
    passaddy(a);
    cout << a << endl;

    return 0;
}
Austin
  • 6,921
  • 12
  • 73
  • 138

1 Answers1

0

In this case, references are superior because you cannot make all the common mistakes of pointers--references must always point to the type of object they reference, and cannot ever be NULL or nullptr, which automatically eliminates many of the headaches of dealing with pointers.

Some compilers can use pointers to implement references, but the two do have different semantics. These semantics are useful in different cases. Here, it's just easier not to have to remember to dereference the pointer--it's another pesky layer of abstraction that you won't trip over when you code. In other cases, it might be favourable to be able to have a NULL pointer or reference.

CinchBlue
  • 6,046
  • 1
  • 27
  • 58
  • You're contradicting yourself. First you say references are superior, then that they have different semantics (the latter is actually true). Oranges beat the hell out of apples! At being orange! – Blindy Jul 08 '15 at 04:46