Click here to Skip to main content
13,864,474 members
Click here to Skip to main content
Add your own
alternative version


1 bookmarked
Posted 18 Feb 2012
Licenced CPOL

Swap Two Numbers without using Temp Variable

, 18 Feb 2012
Rate this:
Please Sign up or sign in to vote.
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;


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


About the Author

United States United States
No Biography provided

You may also be interested in...


Comments and Discussions

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

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190214.1 | Last Updated 19 Feb 2012
Article Copyright 2012 by GregEllis
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid