DIGIT-ARC read-only archive · snapshot: July 23, 2026

Is it possible to swap two numbers without using a third temporary variable?

10 posts · originally from https://geek.digit.in/community/threads/is-it-possible-to-swap-two-numbers-without-using-a-third-temporary-variable.144700/

D
DIPANSHU_ASRI Original post #1
Aug 5, 2011 at 4:30 PM
please answer if u can.
nims11
nims11 #3
Aug 5, 2011 at 8:09 PM
let x and y be two numbers that have some value.
x = x+y
y=x-y
x=x-y.
mitraark
Aug 5, 2011 at 9:50 PM
Don;t you have a book or something ? You had to create a thread /?
arpanmukherjee1
Aug 5, 2011 at 10:18 PM
Code:
a= a^b;
b = b^a;
a = a^b;
Liverpool_fan
Aug 6, 2011 at 10:29 AM
First of all mention the programming language you are using.

If it's C or C++, above replies will do. Note don't try the one line XOR technique, that is undefined and not portable.

If it's Python
Code:
v1, v2 = v2, v1
Omi
Omi #7
Aug 7, 2011 at 9:46 AM
Use pointers
nims11
nims11 #8
Aug 7, 2011 at 10:52 AM
Use pointers

i think it would still require another variable unless the address of two variables are consecutive.
ss max
ss max #9
Aug 7, 2011 at 11:58 AM
i think it would still require another variable unless the address of two variables are consecutive.
Yes it would require another variable because as soon as you will apply swap on pointer variable the previous value will be gone and you can not do both swaps in single operation.
For swapping follow the approach that nims11 provided.
Liverpool_fan
Aug 7, 2011 at 12:27 PM
Think I should assume the OP is using C/C++ and in that case the thread has run its course.