Swapping function not working!
Can someone tell me whats wrong with these codes?
Why x and y couldnt be swap?
#include <stdio.h>
void swap (int x, int y);
int main()
{
int x, y;
x=3;
y=4;
swap(x, y);
printf("X is %d\n", x);
printf("Y is %d\n", y);
return 0;
}
void swap(int x, int y)
{
int temp;
temp= x;
x=y;
y=temp;
return;
}
Re: Swapping function not working!
You are passing the variables by value.
If using C++, you can pass by reference.
In C/C++, you can pass pointers
Re: Swapping function not working!
Sorry! I still do not quite get it..
May i know what changes should i made to the codes for it to work?
Re: Swapping function not working!
Code:
/* change the prototype */
void swap (int * x, int * y);
/* change the function call */
swap(&x, &y);
/* change the function itself */
void swap(int * x, int * y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
return;
}
Re: Swapping function not working!
The pass-by-reference alternative in C++:
Code:
/* 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.
Re: Swapping function not working!
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!!
Re: Swapping function not working!
@Lindley,
Could you kindly explain in this case, what are we doing to swap x and y since we are not using pointers?
Re: Swapping function not working!
Quote:
Originally Posted by
charleneok
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