Below is the program for swapping variables without any extra variable.

#include "stdio.h"
#include "conio.h"
void main()
{
   int a=7;b=5;
   clrscr();
   a=a+b;
   b=a-b;
   a=a-b;
   getch();
}
a=a+b;
b=a-b;
a=a-b;

Will indeed swap to variables without a temp. Notice that you have to make sure that a+b does not exceed the maximum allowed integer. There is another way of swapping the variables without these constraints:

void swap (int *x, int *y) 
{
   if (x != y) 
   {
      *x ^= *y;
      *y ^= *x;
      *x ^= *y;
   }
}

>> Below is the program for swapping variables without any extra variable.

May I suggest that you view for example this thread ;)

commented: Yes, thanks for pointing that out! +5

hai friend
this code also pretty works to swap two numbers without using a temporary variable and also is the code for swapping two numbers using a single line code

void main()
{

int a=5,b=8;
printf("before swap %d  %d",a,b);
b=(a+b)-(a=b); //swapping code
printf("after swap %d %d",a,b);

}

Very nice work sharagh.satya

thanks mr..
and sorry for saying you spelled my name wrong

If I am not mistaken, that is the xor method no?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.