C语言中swap的作用和用法

如题所述

1.作用:swap的意思是交换两个变量的值,是一个自定义函数。

2.用法使a和b的值进行互换。

例如:void swap(int*p1,int*p2)    //*p1=a;*p2=b;

改变指针指向的地址的值,即a和b的值互换。

3.其他用法

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

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

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

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

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

具体代码如下:

    /*-----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;  

    }  

温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网