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;

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay