Swapping two variables without using a temp variable

December 2016






Using pointers


#include <stdio.h>
void change(int *,int*);

int main ()
{
  int a=2,b=5;
  printf("Before : a=%d,b=%d\n",a,b);

  change(&a,&b);

  printf("After : a=%d,b=%d\n",a,b);
  return 0;
}

void change(int *a,int *b){

  *a += *b;
  *b = *a-*b;
  *a = *a-*b;
}


Results
Before : a=2,b=5
After : a=5,b=2

Making use of a Macro


#include <stdio.h>
#define SWAP(x,y) x ^= y, y ^= x, x ^= y

int main ()
{
  int a=2,b=5;
  printf("Before : a=%d,b=%d\n",a,b);

  SWAP(a,b);

  printf("After : a=%d,b=%d\n",a,b);
  return 0;
}

Results
Before : a=2,b=5
After : a=5,b=2

Note that:
The name of the macro or variables may be changed to your convenience.

Related :

This document entitled « Swapping two variables without using a temp variable » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.