C language swap of a b value exchange of four methods

  • 2020-04-01 21:33:12
  • OfStack

What this article wants to express is really very simple, before writing, I struggled for a long time: to write or not to write. Normally, swap(a,b) value exchange, we are basically using the first method, for people who are good at mathematics, may think of the second method, think of it, must feel good,. Anyone with an understanding of assembly or counterpoint might think of a third method, which is a wonderful one. However, what really prompted me to write this article is the fourth method, wonderful, really wonderful, first (b = a), I really did not expect, I think, such a good thing, although simple, but it is worth publishing, to share.

Four methods of swap(a,b) value exchange:


void swap(int &a, int &b)  
{  
    //Method 1: & NBSP;  
    int tmp = 0;  
    tmp = b;  
    b = a;  
    a = tmp;  
    //Method 2: & NBSP;  
    //a = a+b;   
    //b = a-b;   
    //a = a -b;   
    //Method 3: & NBSP;  
    //a ^= b ^= a ^= b;   
    //Method 4: & NBSP;  
    //a = a+b-(b=a);   
}  

int main(void)  
{  
    int a = 3;  
    int b = 4;  

    printf("before swap: a = %d, b = %dn", a, b);  
    swap(a, b);  
    printf("after swap: a = %d, b = %dn", a, b);  

    return 0;  
}  

Results:

Before swap: a = 3, b = 4

After swap: a = 4, b = 3


There are three methods for passing arguments: value, address, and reference (C++ method). The third method is referred to above, because it makes the implementation of swap more intuitive. Of course, you can also use the second method address, but the value of the parameters is not oh.


Related articles: