2
void swap(int *a, int *b)
{
    int iTemp ;
    iTemp = *a;
    *a = *b;
    *b = iTemp;

}
void swap2(int &a, int &b)
{
    int iTemp;
    iTemp = a;
    a = b;
    b = iTemp;
}

What are the difference between swap2(&a, &b) and swap(*a,*b). Although, final result is the same.

M.M
  • 138,810
  • 21
  • 208
  • 365

1 Answers1

0
void swap(int *a, int *b)

You are expecting the variable to pass by pointer (a value of the type pointer to int)


void swap2(int &a, int &b)

you are expecting the variable to pass by reference (which is the the address of an integer variable)


However, the two previous statements are the same technically.

1) The first one is called like this:

int a,b;
swap(&x,&y);

the other one:

int a,b;
swap2(x,y);

2) You can pass A NULL or nullptr to the first one. However, you can not for the second one.

As far as I remember, in google c++ style guide, they prefer the first one since it is obvious that the parameter may be changed.

Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160