Swap two number variables without using a temp third

Everything else that doesn't fall into one of the other PB categories.
MachineCode
Addict
Addict
Posts: 1482
Joined: Tue Feb 22, 2011 1:16 pm

Swap two number variables without using a temp third

Post by MachineCode »

Today I read how to swap two number variables without using a temp third. This is much slower than using PureBasic's "Swap" command, and doesn't take data type limits into account, which is why I didn't post it as a "tip"; but I think it's cool anyway. I never knew it could be done by maths like this. Does anyone know any other ways?

Code: Select all

a=12345
b=67890
a+b : b=a-b : a-b
Debug a
Debug b
Microsoft Visual Basic only lasted 7 short years: 1991 to 1998.
PureBasic: Born in 1998 and still going strong to this very day!
User avatar
idle
Always Here
Always Here
Posts: 6238
Joined: Fri Sep 21, 2007 5:52 am
Location: New Zealand

Re: Swap two number variables without using a temp third

Post by idle »

Can't say that it occurred to me to swap that way with add and subtract
you can do the same with or and xor

Code: Select all

a=12345
b=67890
a|b : b!a : a!b
Debug a
Debug b
Windows 11, Manjaro, Raspberry Pi OS
Image
User avatar
graph100
Enthusiast
Enthusiast
Posts: 115
Joined: Tue Aug 10, 2010 3:17 pm

Re: Swap two number variables without using a temp third

Post by graph100 »

remain the problem of the high number :)
if the sum is higher than the type allow.
_________________________________________________
My Website : CeriseCode (Warning : perpetual changes & not completed ;))
eesau
Enthusiast
Enthusiast
Posts: 589
Joined: Fri Apr 27, 2007 12:38 pm
Location: Finland

Re: Swap two number variables without using a temp third

Post by eesau »

Code: Select all

A = 1
B = 2

; Let's swap them without using a temp third variable

B = 1
A = 2
:P
Post Reply