Sunday, May 8, 2011

Swapping without using temporary variable in C - XOR

/**
* Swapping without using a temporary variable in C
* (XOR)
**/
#include<stdio.h>
int main(void)
{
int a = 5; /* a = 0101 */
int b = 10; /* b = 1010 */
printf("Initially, a = %d and b = %d\n", a, b);
a = a ^ b; /* a = 0101 XOR 1010 = 1111 */
b = a ^ b; /* b = 1111 XOR 1010 = 0101 */
a = a ^ b; /* a = 1111 XOR 0101 = 1010 */
printf("After swapping, a = %d and b = %d\n", a, b);
return 0;
}
view raw swap_xor.c hosted with ❤ by GitHub
Written by

No comments:

Post a Comment