Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Difference Between func(int &param) and func(int *param)?

In the following code, both amp_swap() and star_swap() seems to be doing the same thing. So why will someone prefer to use one over the other? Which one is the preferred notation and why? Or is it just a matter of taste?

#include <iostream>

using namespace std;

void amp_swap(int &x, int &y)
{
    int temp = x;
    x = y;
    y = temp;
}

void star_swap(int *x, int *y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}

int main()
{
    int a = 10, b = 20;
    cout << "Using amp_swap(): " << endl;
    amp_swap(a, b);
    cout << "a = " << a << ", b = " << b << endl;
    cout << "Using star_swap(): " << endl;
    star_swap(&a, &b);
    cout << "a = " << a << ", b = " << b << endl;
    return 0;
}

Thanks for your time!


See Also

Difference between pointer variable and reference variable in C++

like image 482
Srikanth Avatar asked Oct 10 '08 08:10

Srikanth


People also ask

What is the difference between int& and int?

int& is a reference to int variable. Reference is something very close to the pointer. The main difference is that the reference is constant, so it should be assigned immediately after initialization and you can do no pointer arithmetics with reference.

What does int &X mean?

INT(x) rounds the number x down to an integer.

What does &A mean in C++?

&a means "address of a" only when used outside function declarations.

What does int& mean in C++?

A int& return type simply means it returns a reference (address) of an EXISTING integer variable, same goes for int& as an argument, the function takes a reference to an integer instead of creating a new variable copy of it.


1 Answers

One is using a reference, one is using a pointer.

I would use the one with references, because you can't pass a NULL reference (whereas you can pass a NULL pointer).

So if you do:

star_swap(NULL, NULL);

Your application will crash. Whereas if you try:

amp_swap(NULL, NULL); // This won't compile

Always go with references unless you've got a good reason to use a pointer.

See this link: http://www.google.co.uk/search?q=references+vs+pointers

like image 124
Mark Ingram Avatar answered Sep 28 '22 05:09

Mark Ingram