iansmathew
iansmathew

Reputation: 387

What's wrong with this swap function using pointers?

Still a noob to programming in general. I know this code doesn't work but why?

void swap(int num1, int num2)
{ 
  int* p_first =& num1;
  int* p_sec =& num2;
  *p_first = num1;
  *p_sec = num2; 
}

Upvotes: 0

Views: 967

Answers (3)

Akankshi Mishra
Akankshi Mishra

Reputation: 65

1 - Here in the swap function you are using call by value so u cant get the result back in caller function.

2 - Implement the function given below ->

void swap(int num1, int num2) { 
    int temp;
    int* p_first =&num1;
    int* p_sec =&num2;
    temp = *p_first;
    *p_first = *p_sec;
    *p_sec = temp;
    printf("\n %d %d \n",num1,num2);
}

Swap will work now.

Upvotes: -2

Van Tr
Van Tr

Reputation: 6101

Your function does nothing at all, it look like a no-output function.

The reason is: num1, num2 are stack variables, you assign their address to p_first and p_sec which are also stack variable. Address of stack variable will be changed every time you execute the code.

And if you want to swap num1 and num2 why did you assign there values to two others variables (which make no sense).

At least you should think like this to swap them:

temp = num1
num1 = num2
num2 = temp

and because C++ will just pass value to function if you declare like this

void swap(int num1, int num2)

so you need to use pointer or reference to do it (the detail implementation could be searched easily):

void swap(int* num1, int* num2) //pointer parameter
void swap(int& num1, int& num2) //reference parameter

Upvotes: 1

Ryan Bemrose
Ryan Bemrose

Reputation: 9266

The function takes its arguments by value, which means that the function is only operating on temporary copies of num1 and num2. The function modifies those values, and then when it returns, it throws away the temporary values, and the unchanged real values are kept.

The idiomatic C++ way to fix this is pass arguments by reference instead of value.

void swap(int &num1, int &num2) {
   auto temp = num1;
   num1 = num2;
   num2 = temp;
}

int x = 5, y = 7;
swap(x, y);

Alternatively, you can pass the arguments by pointer. This is the idiomatic C way to do it (as C doesn't have references). The disadvantage is that it forces the caller's code to pass the address of its arguments, rather than the arguments themselves.

void swap(int *num1, int *num2) {
   int temp = *num1;
   *num1 = *num2;
   *num2 = temp;
}

int x = 5, y = 7;
swap(&x, &y);

Of course, to swap two numbers, the best way is to not reinvent the wheel, and instead use std::swap, which is already written for you.

int x = 5, y = 7;
std::swap(x, y);

Upvotes: 2

Related Questions