4

Possible Duplicate:
difference between a pointer and reference parameter?

Using C++ i'm wondering what's the difference in the use of & and * in parameters?

For example:

void swap(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

That apparently would swap the integers a and b. But wouldn't the following function do exactly the same?

void swap(int *a, int *b)
{
    int temp = *b;
    *b = *a;
    *a = temp;
}

I was just wondering when it is appropriate to use each one, and perhaps the advantages of each one.

Community
  • 1
  • 1
Paul Thompson
  • 3,290
  • 2
  • 31
  • 39
  • 4
    The usual motto is "use references when you can, pointers when you have to". – Matteo Italia Nov 11 '12 at 02:56
  • 4
    Also, see [here](http://stackoverflow.com/questions/57483/what-are-the-differences-between-pointer-variable-and-reference-variable-in-c) and [here](http://stackoverflow.com/questions/620604/difference-between-a-pointer-and-reference-parameter). – Matteo Italia Nov 11 '12 at 02:57
  • Also [this](http://stackoverflow.com/questions/9636903/what-are-the-distinctions-between-the-various-symbols-etc-combined-with-p) – bames53 Nov 11 '12 at 03:12

1 Answers1

3

The difference between pointers and references is that pointers can point to "nothing", while references cannot. Your second sample should null-check pointers before dereferencing them; there is no need to do so with references.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Indeed, one of good coding practice that one can follow is input arguments (which you do not want to copy) should be const references instead of pointers and output can be pointers. That way you do not have to check for input-args being null, and if there are any problems then caller of function needs to deal with that – Sarang Nov 11 '12 at 05:18