#include <stdio.h>
void swap1(int a, int b)
{
int temp = a;
a = b;
b = temp;
}开发者_StackOverflow
void swap2(int *a, int *b)
{
int *temp = a;
a = b;
b = temp;
}
void swap3(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
main()
{
int a = 9, b = 4;
printf("%d , %d\n", a, b);
swap1(a, b);
printf("%d , %d\n", a, b);
swap2(&a, &b);
printf("%d , %d\n", a, b);
swap3(&a, &b);
printf("%d , %d\n", a, b);
}
C has value semantics for function parameters. This means the a
and b
for all your three swap variants are local variables of the respective functions. They are copies of the values you pass as arguments. In other words:
swap1
exchanges values of two local integer variables - no visible effect outside the functionswap2
exchanges values of two local variables, which are pointers in this case, - same, no visible effectswap3
finally gets it right and exchanges the values pointed to by local pointer variables.
You're swap2
function has no effect.
You are passing in two pointers. Inside the function, the (parameter) variables a
and b
are local to the function. The swap2
function just swaps the values of these local variables around - having no effect outside the function itself.
As Anon pointed out, swap1
has the same problem - you're just modifying local variables.
swap1
will not work because the function just copied the arguments, not affecting the variables in main
.
swap2
will not work either.
swap1()
and swap2()
have an effect limited to the scope of the function itself: the variables they swap are parameters passed by copy, and any change applied to them does not impact the source variable of your main()
that were copied during the function call.
swap3
works as it acts on the values pointed by the parameters, instead of acting on the parameters themselves. It is the only of the three that chage the value located at the memory adress in which your main()
's a
and b
variables are stored.
Just for fun, exchange values without the use of a temporary variable
x = x ^ y
y = x ^ y
x = x ^ y
精彩评论