C/C++ How does this swap function work in C++?

  • Thread starter Thread starter needOfHelpCMath
  • Start date Start date
  • Tags Tags
    Coding Explanation
Click For Summary
The discussion revolves around a C++ code snippet that demonstrates how a swap function operates with reference and value parameters. The code defines a function `Swap` that takes an integer reference and a value. When the function is called in `main`, the output is `12 12`, which confuses some participants. The key point is that the reference parameter `x` allows modifications to affect the variable `b`, while the value parameter `y` does not affect `a`. Thus, the swap function does not achieve its intended purpose of swapping the values of `a` and `b`. To correctly swap both values, the function signature should be modified to accept both parameters as references, changing it from `void Swap(int& x, int y)` to `void Swap(int& x, int& y)`. This adjustment would enable the function to swap the values of both variables effectively.
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)
 
Anthropic announced that an inflection point has been reached where the LLM tools are good enough to help or hinder cybersecurity folks. In the most recent case in September 2025, state hackers used Claude in Agentic mode to break into 30+ high-profile companies, of which 17 or so were actually breached before Anthropic shut it down. They mentioned that Clause hallucinated and told the hackers it was more successful than it was...

Similar threads

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