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

  • Thread starter Thread starter needOfHelpCMath
  • Start date Start date
  • Tags Tags
    Coding Explanation
AI Thread 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)
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.

Similar threads

Back
Top