Swapping two variables without using a temp variable

June 2017






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


Published by jak58. Latest update on August 9, 2009 at 11:04 AM by jak58.
This document, titled "Swapping two variables without using a temp variable," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).