0 Replies - 1885 Views - Last Post: 13 July 2011 - 09:16 PM Rate Topic: -----

#1 stackoverflow   User is offline

  • D.I.C Addict
  • member icon

Reputation: 166
  • View blog
  • Posts: 545
  • Joined: 06-July 11

Three different swap methods

Posted 13 July 2011 - 09:16 PM

Description: I have included 3 function definitions and a sample usage with output. I have not included error checks-- those are left up to the caller. These are 3 different swap methods that can be used to swap two variables. These do not use ASM as one of the other snippets used.
#include <stdio.h>

/* tempSwap - uses a third variable to swap two variables
* @first: the first variable you wish to use
* @second: the second variable you wish to use
*/
void tempSwap(int *first, int *second)
{
  int temp = *first;
  *first = *second;
  *second = temp;
} 

/* xorSwap - uses the binary xor operator to swap 
* @first: the first variable you wish to use
* @second: the second variable you wish to use
*/
void xorSwap(int *first, int *second)
{
  *first ^= *second ^= *first ^= *second;
}

/* addSubSwap - uses addition and subtraction to swap
* @first: the first variable you wish to use
* @second: the second variable you wish to use
*/
void addSubSwap(int *first, int *second)
{
  *first = *first + *second;
  *second = *first - *second;
  *first = *first - *second;
}

int main(void)
{
  int ten = 10;
  int one = 01;
  
  /* ten should become 01 and one should become 10 */
  addSubSwap(&ten, &one);
  printf("ten %dnone %dn", ten, one);
 
  /* ten should become 10 and one should become 01 */
  xorSwap(&ten, &one);
  printf("ten %dnone %dn", ten, one);

  /* ten should become 01 and one should become 10 */
  tempSwap(&ten, &one);
  printf("ten %dnone %dn", ten, one);

  return 0;
}


Is This A Good Question/Topic? 0
  • +

Page 1 of 1