DEV Community

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

Posted on

3 1

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

C program to swap two integers without using third variable

#include <stdio.h>
void main() {
int a, b;
printf("Enter two integer values for swapping : ");
scanf("%d %d", &a, &b);
printf("A = %d, B = %d\n", a, b);
a = a + b;
b = a - b;
a = a - b;
printf("After swapping :\n");
printf("A = %d \t, B = %d\n", a, b);
printf("===End===\n");
}

Top comments (4)

Collapse
 
fpuffer profile image
Frank Puffer • Edited

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

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

reduced to one line:

a ^= b ^= a ^= b;

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay