Why do these swap functions behave differently?

社会主义新天地 提交于 2019-11-29 15:58:36

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 function
  • swap2 exchanges values of two local variables, which are pointers in this case, - same, no visible effect
  • swap3 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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!