Skip to content

Instantly share code, notes, and snippets.

@mbalayil
Created May 8, 2011 19:05
Show Gist options
  • Save mbalayil/961596 to your computer and use it in GitHub Desktop.
Save mbalayil/961596 to your computer and use it in GitHub Desktop.
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment