Swap two variables in one line in C/C+

CC++Server Side Programming

Here is an example of swapping in C language,

Example

 Live Demo

#include <stdio.h>
int main() {
   int a = 28, b = 8;
   a += b -= a = b - a; // method 1
   printf("After Swapping : %d\t%d", a, b);
   (a ^= b), (b ^= a), (a ^= b); // method 2
   printf("\nAfter Swapping again : %d\t%d", a, b);
   return 0;
}

Output

After Swapping : 828
After Swapping again : 288

In the above program, there are two variables a and b and initialized with the values 28 and 8 respectively. There are so many methods to swap two numbers in one line and we displayed two methods here.

a += b -= a = b - a; // method 1
printf("After Swapping : %d\t%d", a, b);
(a ^= b), (b ^= a), (a ^= b); // method 2
printf("\nAfter Swapping again : %d\t%d", a, b);
raja
Published on 06-Nov-2018 06:07:23
Advertisements