DEV Community

Cover image for Swap two integers in 'C' programming Without using third variable
Rushikesh
Rushikesh

Posted on

Swap two integers in 'C' programming Without using third variable

C program to swap two integers without using third variable

Discussion (4)

Collapse
fpuffer profile image
Frank Puffer • Edited on

While it does have some educational value to show that this is possible, this method has two issues:

  • Both a = a + b and a = a - b can cause an overflow.

  • I can't imagine many situations where saving a few bytes really makes up for the loss in readability.

Collapse
semiversus profile image
Günther Jena • Edited on

It also works with XOR (avoiding the overflow problem):

a = a ^ b
b = a ^ b
a = a ^ b
Enter fullscreen mode Exit fullscreen mode
Collapse
codemouse92 profile image
Jason C. McDonald

Agreed, this is definitely the way to do it.

Collapse
joecar7 profile image
Joe Carnuccio • Edited on

reduced to one line:

a ^= b ^= a ^= b;