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.

3
  • 4
    The usual motto is "use references when you can, pointers when you have to". Commented Nov 11, 2012 at 2:56
  • 4
    Also, see here and here. Commented Nov 11, 2012 at 2:57
  • Also this Commented Nov 11, 2012 at 3:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.