/* Change the prototype */
void swap (int &x, int &y);
/* No change required at call */
/* Again change the prototype, but no change required to the function body */
void swap(int &x, int &y)
{
int temp;
temp= x;
x=y;
y=temp;
return;
}
Of course, in C++ you can just use std::swap(); there's no need to write your own.
It works!
Could you kindly explain why we have to use pointers instead of just swapping the value directly?
and for the function call, it is compulsory to add in the '&'??
Thanks a lot!!
It works!
Could you kindly explain why we have to use pointers instead of just swapping the value directly?
You seem to be making the mistake in believing that the "x" and "y" in the swap function are the same "x" and "y" you declared in main(). They are not -- they are just names for the parameters being passed. They could be called "Joe" and "Bill" instead of x and y in the swap function -- the results would be the same.
You need to learn the difference in parameter passing -- pass-by-value, pass-by-reference, pointers, etc.
Look at this simple program:
Code:
void func(int x)
{
x = 10;
}
void func2(int* x)
{
*x = 10;
}
void func3(int& x)
{
x = 20;
}
int main()
{
int myValue = 1;
func(myValue);
// why is myValue still 1?
func2(&myValue);
// Now it has changed to 10;
func3(myValue);
// Now it has changed to 20;
}
Regards,
Paul McKenzie
Last edited by Paul McKenzie; November 9th, 2011 at 01:20 PM.
Bookmarks