c - Why do these swap functions behave differently? -
#include <stdio.h> void swap1(int a, int b) { int temp = a; = b; b = temp; } void swap2(int *a, int *b) { int *temp = a; = b; b = temp; } void swap3(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } main() { int = 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 function parameters. means a
, b
3 swap variants local variables of respective functions. copies of values pass arguments. in other words:
swap1
exchanges values of 2 local integer variables - no visible effect outside functionswap2
exchanges values of 2 local variables, pointers in case, - same, no visible effectswap3
gets right , exchanges values pointed to local pointer variables.
Comments
Post a Comment