«« Site Rescued »»

While the site is still going to move from its current host, a new site will now take its place. More Info.

The new site may have less content, but the core will now remain. And it will now play nicely with phones! Keep an eye on the DelphiDabbler Blog for news.

» Help

How to swap two integers without using a temporary variable


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);
  A, B: Integer;
  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);

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

« Return to contents »