Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
The same way one swaps the liquid in two cups without any intermediate storage space.
Quite the brain teaser, and an age-old question. If I remember my physics correctly, one crux is that "two objects cannot occupy the same space at the same time".
The only ways I know of, rely on a twist on the words, like storing in registers rather than allocated variables (if it fits), or swapping pointers to values (if applicable). Yet a temp container still needs to be used for one value of some sort. I'd love to hear more creative solutions...
Cheers

Hi - In programming, this is typically done using XOR functions/transformations.
It can be done with data in registers or variables if the language you use supports this.
It usually cannot be done with user defined objects in an OO language (tho' there are some exceptions here).
For example (in Java):
int i = 2;
int j = 3;
System.out.println("i= "+i+" j= "+j);
i = i ^ j;
j = j ^ i;
i = i ^ j;
System.out.println("i= "+i+" j= "+j);HTH, Guy

There are two ways you can swap two variables
Method #1 this works integers and floats
a=12 :b=4
a=a+b
b=a-b
a=a-bmethod #2 Integers only
a=12 : b=4
a=a xor b
b=a xor b
a=a xor bif your computer doe's not have an XOR function use (a or b) and not (a and b)
as below.
a=(a or b)and not (a and b)
b=(a or b) and not (a and b)
a=(a or b)and not (a and b)

If you're programming in assembly, there is actually an xchg instruction. At least one of your operands has to be in a register, but it can be done in one instruction.

Ah yes - I had forgotten that languages like Java (and others) forbid XOR on primitives like floats and doubles (although this is not usually a consideration in assembly language).
If XOR is forbidden, then the method#1 above works fine.
The 'xchg' instruction is of course OK on Intel architecture machines. Machines from other vendors may or may not have an equivalent instruction. Most will allow the XOR technique, for example to swap the values in two registers on a IBM mainframe:
XR R1,R2
XR R2,R1
XR R1,R2Much more difficult on for example a PDP-8, so named because there are only 8 instructions in the whole set, and if I recall correctly a single 8-bit data register.
Regards, Guy

Please ignore my initial theoretical blather, Nirav. I should have realised you simply meant how to avoid allocating your own integers, rather than hypothesise whether temp storage could be avoided at all (e.g., registers, whether instruction-loaded or not). Everyone else addressed your question quite nicely.
Cheers

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |