Search code examples
c++swap

Despite everything looks fine, values are not swapped


I wanted to write a function to swap two integers. Despite everything looks fine, values are not swapped.

Here is my code:

#include <iostream>

using namespace std;

void mySwap(int a, int b)
{
  int temp;
  temp = a;
  a = b;
  b = temp;
}

int main()
{
  int a = 5, b = 4;
  mySwap(a, b);
  cout << a << ' ' << b << endl;
  return 0;
}
Output: 5 4

Please, help me understand the reason. Any help is appreciated.


Solution

  • To manipulate with the values passed as arguments in main() directly, use a reference (followed by an ampersand sign &) as shown:

    #include <iostream>
    
    void mySwap(int& a, int& b) // using reference here
    {
        int temp; // remove for alternative option described at the bottom
        temp = a; // a = a + b;
        a = b;    // b = a - b;
        b = temp; // a = a - b;
    }
    
    int main(void)
    {
        int a = 5, b = 4;
    
        mySwap(a, b); // passed 5, 4 and original values are manipulated.
    
        std::cout << a << ' ' << b << std::endl;
    
        return 0;
    }
    

    As soon as you pass the variables as the function arguments, it'll change originally too.

    On the contrary, if you don't use that, the program will just create two local variables that will only be visible inside the function, then even after swapping them, you won't get success.


    Another method of swapping between two variables (without a temporary variable):

    a = a + b;
    b = a - b;
    a = a - b;