How does this swap function work in C++?

  • Context: C/C++ 
  • Thread starter Thread starter needOfHelpCMath
  • Start date Start date
  • Tags Tags
    Coding Explanation
Click For Summary
SUMMARY

The forum discussion clarifies the behavior of the swap function in C++. The provided code demonstrates that the function signature 'void Swap(int& x, int y)' allows modifications to the variable 'b' but not to 'a', resulting in the output '12 12'. To achieve the intended swap of values between 'a' and 'b', the function signature must be changed to 'void Swap(int& x, int& y)'. This adjustment ensures that both variables are passed by reference, allowing for the correct swapping of values.

PREREQUISITES
  • Understanding of C++ reference variables
  • Familiarity with function signatures in C++
  • Basic knowledge of variable scope and lifetime in C++
  • Experience with output streams in C++ (e.g., cout)
NEXT STEPS
  • Research C++ reference variables and their usage
  • Learn about function overloading in C++
  • Explore the concept of passing parameters by reference vs. by value
  • Investigate common pitfalls in C++ function implementations
USEFUL FOR

C++ developers, programming students, and anyone looking to deepen their understanding of function behavior and parameter passing in C++.

needOfHelpCMath
Messages
70
Reaction score
0
I can't understand how this code was able to swap or get this output:

Code:
	Based off of the following code what is the output of the main function?
void Swap(int& x, int y){				
	int temp = x;				
	x = y;						
	y = temp;					
	return;						
}						
				
int main(){

int a =12;
int b = 3;

Swap( b, a);
cout << a << “ “ << b << endl;return 0;
}

output : 12 12
 
Technology news on Phys.org
Well if you look at the swap method signature, there is 'int & x' which means it takes the reference of the variable that's passed to the method, while 'int y' will only take the value of the variable that is passed to the method.

So since b is passes to the x in the swap function, what ever you do to x inside the function will actually affect the variable b.

But since only the value of a is passed to y, even if you changed the value of y nothing will happen to the value of a.

But since this is a swap function and actual requirement is to swap the values of a and b you should change the method signature from

Code:
void swap(int & x, int y)
to
Code:
void swap(int & x, int & y)
 

Similar threads

  • · Replies 19 ·
Replies
19
Views
6K
  • · Replies 1 ·
Replies
1
Views
1K
Replies
63
Views
5K
  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 23 ·
Replies
23
Views
3K
  • · Replies 13 ·
Replies
13
Views
2K
Replies
12
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 6 ·
Replies
6
Views
1K
  • · Replies 25 ·
Replies
25
Views
3K