0

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.

VIVID
  • 555
  • 6
  • 14
  • 1
    If this is not purely for educational purposes, you could use [`std::swap`](https://en.cppreference.com/w/cpp/algorithm/swap) – Ted Lyngmo Jun 25 '20 at 07:50

3 Answers3

3

You are copying arguments a and b. Change them to reference.

void mySwap(int & a, int & b)
2

What you are doing right now is swapping a local Copy of the variables instead of the real variables.

What you need to do, to fix it is to change your function a little bit(just add &, this makes it take a reference of the variables and not create a local copy of them)

void mySwap(int &a, int &b)
{
  int temp;
  temp = a;
  a = b;
  b = temp;
}
IndieGameDev
  • 2,905
  • 3
  • 16
  • 29
1

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;
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34