swap c++/ reference

closed account (Nwb4iNh0)
Is really necessary to use reference variable when create function to swap elements like below!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  
void swap(int & Num1, int & NUm2) {
    int temp = Num1;          
    Num1 =NUm2;
    NUm2 = temp;
}


//

void swap(int Num1, int Num2){
int temp;
temp = Num1;
Num1 = Num2;
Num2 = temp;
}

Yes. Otherwise the changes aren't reflected back in the calling function. For Pass by value (if a ref isn't used) the param variables are effectively local with initial values obtained from the calling function.
it is necessary to ensure the values are modified. You can do that with pointers instead, but that is ugly and usually best avoided. You can also craft an inline swap (like a macro, also a bad idea) that does it directly. Basically, there are alternatives, but nothing any better and most notably worse.

If you did not know, c++ has a swap function already, which is the right way to do it if not studying swap logic or forced to DIY in schoolwork.
closed account (Nwb4iNh0)
Thanks for help guys :)
Without reference (or pointer) parameters swapping the two numbers in the function will have no effect because you are copying the numbers when passed to the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>

void fake_swap(int num1, int num2);
void ref_swap(int& num1, int& num2);
void ptr_swap(int* num1, int* num2);

int main()
{
   int num1 { 5 };
   int num2 { 257 };

   // swap with copied parameters
   std::cout << "Before swapping: " << num1 << ", " << num2 << '\n';

   fake_swap(num1, num2);

   std::cout << "After swapping:  " << num1 << ", " << num2 << "\n\n";

   // swap with referenced parameters
   std::cout << "Before swapping: " << num1 << ", " << num2 << '\n';

   ref_swap(num1, num2);

   std::cout << "After swapping:  " << num1 << ", " << num2 << "\n\n";

   // swap with pointer parameters
   std::cout << "Before swapping: " << num1 << ", " << num2 << '\n';

   ptr_swap(&num1, &num2);

   std::cout << "After swapping:  " << num1 << ", " << num2 << '\n';
}

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

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

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


closed account (Nwb4iNh0)
Great, but isnt the reference swap as same as pointer swap?
a pointer is a lot like a reference, but a pointer is NOT a reference. The idea is the same, and in some cases the generated machine language may be the same, but even so it is not safe to say they are the same things. So, 'almost' but 'no, not really'.
Topic archived. No new replies allowed.