Funcao - swap sem ponteiros nem terceira var |
Top Previous Next |
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; |