Mirror

Swapping two variables without pointers or a third one (Views: 300)


Problem/Question/Abstract:

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.

procedure TForm1.Button1Click(Sender: TObject);
var
  var1: integer;
  var2: integer;
begin

  var1 := 19;
  var2 := 564;

  var1 := var1 xor var2;
  var2 := var1 xor var2;
  var1 := var1 xor var2;

  // Theyīre swapped!!!

  Label1.Caption := 'Var1 = ' + IntToStr(var1) + '; Var2 = ' + IntToStr(var2);
end;


Solve 2:

// ========================================
// This is a FAST swap routine that swaps
// the contents of any 2 variables.
// The variables may be of any type but
// the sizeof the VARS must be passed in Len
//
// eg.  X1,X2 : integer;
//
//        SwapMem(X1,X2,SizeOf(Integer));
//
// ======================================== }

procedure SwapMem(var Source, Dest; Len: integer);
begin
  asm
         push edi
         push esi
         mov esi,Source
         mov edi,Dest
         mov ecx,Len
         cld
     @1:
         mov al,[edi]
         xchg [esi],al
         inc si
         stosb
         loop @1
         pop esi
         pop edi
  end;
end;

<< Back to main page