C Integer swap





8
Date Submitted Wed. Sep. 27th, 2006 8:01 PM
Revision 1 of 1
Beginner zywien
Tags C | swap
Comments 5 comments
Nifty way to swap two integers in C (C++) without using a temporary variable. Uses one line of code (3 assignments).

int x = 3;
int y = 5;
printf("Before\n[x, y] = [%d, %d]\n", x, y);
x ^= y ^= x ^= y;
printf("After\n[x, y] = [%d, %d]\n", x, y);
 

Output::
Before
[x,y] = [3,5]
After
[x,y] = [5, 3]

Jarrod Zywien

Comments

Comments Swap optimization
Mon. Oct. 9th, 2006 10:19 AM    Scripter sehrgut
Comments clever, but..
Sat. Sep. 30th, 2006 8:51 AM    Newbie nanika
  Comments Agree
Mon. Oct. 9th, 2006 6:30 AM    Helper shell
  Comments I agree
Mon. Oct. 2nd, 2006 9:32 AM    Scripter ctiggerf
Comments best as macro
Mon. Oct. 9th, 2006 9:07 PM    Newbie ksadya

Voting