need help swaping integers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <stdlib.h>

using namespace std;

void swap_integers(int x, int y);

int main()
{
    int num1 = 15;
    int num2 = 16;
    cout << num1 << " " << num2 << endl;
    swap_integers(num1,num2);
    cout << num1 << " " << num2 << endl;
    system("Pause");
    return 0;
}

void swap_integers(int x, int y)
{
    int atemp = x;
    x = y;
    y = atemp;
}

i get

15 16
15 16
Press any key to continue . . .

should be

15 16
16 15
Press any key to continue . . .


what am i doing wrong?
you're passing x and y into the swap function by value, which means a copy is made of them and those copies are the only things which are swapped, not the original values.

Pass them in by reference to solve this.
And if you don't have to implement your own, try std::swap.
The most efficient way to swap two variables is with the XOR method :)
1
2
3
x ^= y;
y ^= x;
x ^= y;
The most efficient way to swap two variables is with the XOR method :)


[citation needed]

That method only works with integers, and involves 3 operations.

The more traditional approach:
1
2
3
T temp = x;
x = y;
y = temp;

works with any copyable type T and also only involves 3 operations.

Note that std::swap effectively does exactly that.

I suppose the temp method is "less efficient" in that it needs an additional register for the temporary. But come on.
Hehe I suppose that's true. It doesn't even matter as this is a rather trivial task. The only time I can think of where swapping variables would be necessary is when sorting an array, and there are plenty of library functions for that.
Well actually, the temp variable swapping is more efficient because you need to make sure x != y or XOR wont work, so that's an added statement :)
You should pass x and y by reference:
1
2
3
4
5
6
void swap_integers(int &x, int &y)
{
      int atemp = x;
      x = y;
      y = atemp;
}

And btw, avoid using system functions - such as system("Pause").
Topic archived. No new replies allowed.