How to swap two integers without using a temporary variable #180

You can exchange two integers without using a third temporary variable as follows, assuming A and B are integers with values assigned:

A := A + B;
B := A - B;
A := A - B;

To demonstrate this, drop two TEdit controls and one TButton on a form in a new Delphi VCL forms project and create an OnClick event handler for the button as follows:

procedure TForm1.Button1Click(Sender: TObject);
var
  A, B: Integer;
begin
  A := StrtoInt(Edit1.Text);
  B := StrtoInt(Edit2.Text);
  A := A + B;
  B := A - B;
  A := A - B;
  Edit1.Text := InttoStr(A);
  Edit2.Text := InttoStr(B);
end;

Now enter a numbers in both edit controls. Clicking the button should swap the numbers in the controls.

Author: Unknown
Contributor: Muhammad Saied
Added: 2012/06/18
Last updated: 2012/06/18