C/C++ Swap without using extra variable

来源:互联网 发布:pdf阅读器源码 编辑:程序博客网 时间:2024/05/16 05:19


本系列文章由 @YhL_Leo 出品,转载请注明出处。
文章链接: http://blog.csdn.net/yhl_leo/article/details/50255379


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

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

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

/*** 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}
1 0
原创粉丝点击