28.2.08

Swap the two numbers

This is the most frequently asked C question.

How to swap two numbers without using temporary variable.

There are many ways to do that, here are some.

Code snippets:
1)

int x, y; /* are the two numbers */
x = x+y;
y = x - y;
x = x - y;

2)
x = x*y;
y = x/y;
x = x/y;
3)
x = x ^ y;
y = x ^ y ;
x = x ^ y ;
NOTE: These logics have some limitations
Logic 1 has the Overflow problem when we add (x+y).
Logic 2 has the Overflow problem when we multiply ( x*y) and y should not be Zero.
Logic 3 has the same and its not works on the float numbers.