Possible Duplicate:
Why do these swap functions behave differently?
Have a look at the code below, aimed to swap two numbers, but it does not. Please help me to understand the reason why it does not. I am new to programming, so I would be grateful if you explain the things more than usual.
Thank you!
#include <stdio.h>
void swap (int a, int b);
int main (void)
{
int x = 1;
int y = 2;
swap (x, y);
printf ("Now x is %d and y is %d\n", x, y);
return 0;
}
//function definition of swap
void swap (int a, int b)
{
int temp = a;
int a = b;
int b = temp;
}
C is pass-by-value, so the
swapfunction receives copies of the values, and cannot affect the variables in the caller.To affect the variables in the caller, you need to pass pointers to them.
and call it
in
main.