How to swap two variables in one line in C?
C program to swap two variables in single line
#include <stdio.h>
void main()
{
int a = 5;
int b = 10;
(a ^= b), (b ^= a), (a ^= b);
printf("Swapped values of a and b are %d %d",a, b);
}
Output:
Swapped values of x and y are 10 5
Explanation:
Comma operator has least precedence and associativity is from left to right.In this C program in third line the expression is separated by comma,so evaluation is from left to right.By using comma operator the expression can be of one line and XOR is used to swap values of a and b.
a = a XOR b which is 15
b = b XOR a which is 5
a = a XOR b which is 10
0 Comment(s)