Click here to Skip to main content
15,880,469 members
Articles / Programming Languages / Java
Alternative
Tip/Trick

Swap Two Numbers without using Temp Variable

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
18 Feb 2012CPOL 28.5K   1   5
You can do it with some XORs:int a = 25, b = 7;a = a ^ b;b = b ^ a;a = a ^ b;Or the same thing with some shorthand to make the code even harder to read:a ^= b;b ^= a;a ^= b;
You can do it with some XORs:

int a = 25, b = 7;

a = a ^ b;
b = b ^ a;
a = a ^ b;

Or the same thing with some shorthand to make the code even harder to read:
a ^= b;
b ^= a;
a ^= b;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionswap without using temp variable Pin
iSkyTreasure29-Aug-12 6:09
iSkyTreasure29-Aug-12 6:09 
Questionw/o vs with : which one is fastest? Pin
Alex Ten28-Apr-12 3:45
Alex Ten28-Apr-12 3:45 
GeneralProbably the most useful varient of this was on the old IBM ... Pin
Chuck O'Toole19-Feb-12 9:17
Chuck O'Toole19-Feb-12 9:17 
GeneralReason for my vote of 5 That's *the* established way since t... Pin
Andreas Gieriet19-Feb-12 8:18
professionalAndreas Gieriet19-Feb-12 8:18 
GeneralI prefer: a ^= b; b ^= a; a ^= b; because: 1. no overflow ... Pin
Huisheng Chen18-Feb-12 18:53
Huisheng Chen18-Feb-12 18:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.