SWAP()

There are three common different versions of SWAP function on the internet.

  1. SWAP_v1: Need additional space.
  2. SWAP_v2: May be overflow.
  3. SWAP_v3: No above risk.
void SWAP_v1(int *a, int*b) 
{
  int temp;                 //Need additional space
  temp = *a;

  *a = *b;
  *b = temp;
}
void SWAP_v2(int *a, int*b)  //
{ 
  *a = *a + *b;              //May be overflow, INT_MAX + INT_MAX
  *b = *a - *b;
  *a = *a - *b;
}
void SWAP_v3(int *a, int*b)
{ 
  if(*a == *b)               //Prevent *a = 0
    return;
  *a = *a ^ *b;
  *b = *a ^ *b;
  *a = *a ^ *b;
}

results matching ""

    No results matching ""