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

twitter logo github logo ・1 min read

C programming (2 Part Series)

1) Swap two integers in 'C' programming 2) Swap two integers in 'C' programming Without using third variable

C program to swap two integers without using third variable

twitter logo DISCUSS (4)
markdown guide
 

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.

 

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

a = a ^ b
b = a ^ b
a = a ^ b
 
 
Classic DEV Post from May 10

If you could change one thing about learning to code, what would it be?

If you could wave a magic wand and make your biggest challenge when you were lear...

Programmer Rushikesh profile image