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 function
  • swap2 exchanges values of 2 local variables, pointers in case, - same, no visible effect
  • swap3 gets right , exchanges values pointed to local pointer variables.

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -