浅析C语言中的5个swap函数

这些操作细节应该多积累,多练才能掌握的好啊!

#include "stdafx.h"

/*-----try to swap the value of a and b, but it does not work out.*/
/*void swap1(int x,int y)
{
	int temp;
	temp = x;
	x = y;
	y = temp;
}*/

/*------using the global variables can implement the swap----*/
/*int a(3),b(5);
//the declarations of a and b in the main function should be commented out.
void swap2()
{
	int temp;
	temp = a;
	a = b;
	b = temp;

}*/
/*----using the pointer to pass the address to the swap function*/
/*void swap3(int *px,int *py)
{
	int temp;
	temp = *px;
	*px = *py;
	*py = temp;
}*/
/*----using the reference operator(&)-----*/
void swap4(int &x, int &y)
{
	int temp;
	temp = x;
	x = y;
	y = temp;
}
/*----meaningless swap---*/
/*void swap5(int *px,int *py)
{
	int *p;
	p = px;
	px = py;
	px = p;
}*/

int main(int argc, char* argv[])
{
	int a(3),b(5);
	printf("before swap:%3d %3d\n",a,b);
	swap4(a,b);
	printf("after swap:%3d %3d\n",a,b);

	return 0;
}

swap1只进行了值传递,所以函数调用结束后形参被释放,不能实现实参的值交换;

swap2直接使用全局变量,这样swap2函数和main函数操作的是同一个变量(地址和值都一样),可以实现值交换;

swap3使用传地址的方式,通过修改内存块来实现变量的值交换,是可以的。

swap4使用引用(&)的方式,这样是给mian函数中待交换的变量起一个别名,并把把别名作为形参在swap4中进行处理,这其实就实现了形参和实参的地址和内容完全一样,当然可以实现值交换,swap4的效果和swap2的一样,但这种定义方式更利于程序的调试和维护,同时也可以减小内存开销。

swap5中虽然也把变量的地址传到了函数中,但在函数内部并没用修改地址指向的内存块而是把地址在形参上完成交换,swap5函数运行结束,所有的工作都会都是,而main函数中的变量也没有实现交换,这种情况和swap1类似。

参考资料:程序设计基础(C语言版)秦军主编,机械工业出版社

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值