Home c++ native swap function, why and how does it work?

native swap function, why and how does it work?

Author

Date

Category

The function swaps values, it was 10 and 20, now it is 20 and 10.
The function must accept two pointers to the int type, and in the end it accepts two variables of the int type, and yet, it is not clear why, the working body of the function “a = b; b = a”, I don’t understand how it works?


Answer 1, authority 100%

You are not running your own swap function, but function from the standard library.
To make it work, you need to remove

usung namespace std;

and redo something like this

# include & lt; iostream & gt;
void swap (int * a, int * b) {
  int temp = * a;
  * a = * b;
  * b = temp;
}
int main () {
  int x1 = 10, x2 = 20;
  std :: cout & lt; & lt; "x1 =" & lt; & lt; x1 & lt; & lt; ", x2 =" & lt; & lt; x2 & lt; & lt; std :: endl;
  swap (& amp; x1, & amp; x2); // Pass links
  std :: cout & lt; & lt; "x1 =" & lt; & lt; x1 & lt; & lt; ", x2 =" & lt; & lt; x2 & lt; & lt; std :: endl;
  return 0;
}

You need to pass references to variables to the function via the & amp; operator. In the body of the function itself, you need to dereference the pointer in order to access the values.


Answer 2

I will offer my own version with the transfer of links in f-iu (nothing really changes, only you will not need to dereference pointers)

# include & lt; iostream & gt;
void swap (int & amp; a, int & amp; b);
int main () {
  int x1 = 10, x2 = 20;
  std :: cout & lt; & lt; "x1 =" & lt; & lt; x1 & lt; & lt; ", x2 =" & lt; & lt; x2 & lt; & lt; std :: endl;
  swap (x1, x2);
std :: cout & lt; & lt; "x1 =" & lt; & lt; x1 & lt; & lt; ", x2 =" & lt; & lt; x2 & lt; & lt; std :: endl;
  system ("pause");
  return 0;
}
void swap (int & amp; a, int & amp; b) {
  int temp = a;
  a = b;
  b = temp;
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions