swapping two variables without a temp variable

suggest code in C to swap two variables without using a temporary variable. preferably a single statement.
falkonAsked:
Who is Participating?
 
proskigConnect With a Mentor Commented:
 b ^= a;
  a ^= b;
  b ^= a;

b and a will be swapped


Note also that it is C++ area
0
 
harrlowCommented:
Using C..

a = a + b;
b = a - b;
a = a - b;
0
 
proskigCommented:
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)
0
 
EliezerGarzaCommented:
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.

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.