Link to home
Start Free TrialLog in
Avatar of falkon
falkon

asked on

swapping two variables without a temp variable

suggest code in C to swap two variables without using a temporary variable. preferably a single statement.
ASKER CERTIFIED SOLUTION
Avatar of proskig
proskig

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of harrlow
harrlow

Using C..

a = a + b;
b = a - b;
a = a - b;
The obvious problem with harrlow's code is that it does not work in general case due to size limit (just suppose that a and b are int's and they are close to INT_MAX)
but you can use:
   a=a-b
   b=a+b
   a=b-a
instead of:
   a=a+b
   b=a-b
   a=a-b
or for extra CPU usage:
   a=a*b
   b=a/b
   a=a/b
or any other of many ways. This is just an academical question, so the important thing is not if it works 100% of the cases or not, but how would you do it.