您的位置:首页 > 编程语言 > C语言/C++

C/C++ Swap without using extra variable

2015-12-10 21:56 190 查看
本系列文章由 @YhL_Leo 出品,转载请注明出处。

文章链接: /article/3664491.html

对于可以线性运算的变量,交换两个变量值的做法,通常我们是这样的:

[code]/**
* Swap the parameters with a temp variable.
* @param a The first parameter.
* @param a The second parameter.
*/
void swap(int& a, int& b)
{
    int temp = a;
    a = b;
    b = temp;
}


稍作变化,就可以不通过临时变量实现:

[code]/**
* Swap the parameters without a temp variable.
* Warning! Susceptible to overflow/underflow.
* @param a The first parameter.
* @param a The second parameter.
*/
void swapNoTemp(int& a, int& b)
{
    a -= b;      // a = a - b
    b += a;      // b = b + (a - b), b gets the original value of a
    a = (b - a); // a = a - (a - b), a gets the original value of b
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: