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

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay