Author: Rafael Cotta
How to swap two integers without a temporary variable or pointers?
Answer:
Solve 1:
Yes, it´s possible to swap the values of two variables without using a third one or
swapping pointers.
How??? The answer is: using xor!!!
Place a label and a button on a form, and put this on Button´s click event.
1 2 procedure TForm1.Button1Click(Sender: TObject);
3 var4 var1: integer;
5 var2: integer;
6 begin7 8 var1 := 19;
9 var2 := 564;
10 11 var1 := var1 xor var2;
12 var2 := var1 xor var2;
13 var1 := var1 xor var2;
14 15 // They´re swapped!!!16 17 Label1.Caption := 'Var1 = ' + IntToStr(var1) + '; Var2 = ' + IntToStr(var2);
18 end;
Solve 2:
19 20 // ========================================21 // This is a FAST swap routine that swaps22 // the contents of any 2 variables.23 // The variables may be of any type but24 // the sizeof the VARS must be passed in Len25 //26 // eg. X1,X2 : integer;27 //28 // SwapMem(X1,X2,SizeOf(Integer));29 //30 // ======================================== }31 32 procedure SwapMem(var Source, Dest; Len: integer);
33 begin34 asm
35 push edi
36 push esi
37 mov esi,Source
38 mov edi,Dest
39 mov ecx,Len
40 cld
41 @1:
42 mov al,[edi]
43 xchg [esi],al
44 inc si
45 stosb
46 loop @1
47 pop esi
48 pop edi
49 end;
50 end;