0
Thanks

A few words of thanks would be greatly appreciated.

Swapping two variables without using a temp variable






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.
0
Thanks

A few words of thanks would be greatly appreciated.

Ask a question
CCM is a leading international tech website. Our content is written in collaboration with IT experts, under the direction of Jeff Pillou, founder of CCM.net. CCM reaches more than 50 million unique visitors per month and is available in 11 languages.

Published by . Latest update on 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 (https://ccm.net/).

0 Comments