Articles   Members Online:
-Article/Tip Search
-News Group Search over 21 Million news group articles.
-Delphi/Pascal
-CBuilder/C++
-C#Builder/C#
-JBuilder/Java
-Kylix
Member Area
-Home
-Account Center
-Top 10 NEW!!
-Submit Article/Tip
-Forums Upgraded!!
-My Articles
-Edit Information
-Login/Logout
-Become a Member
-Why sign up!
-Newsletter
-Chat Online!
-Indexes NEW!!
Employment
-Build your resume
-Find a job
-Post a job
-Resume Search
Contacts
-Contacts
-Feedbacks
-Link to us
-Privacy/Disclaimer
Embarcadero
Visit Embarcadero
Embarcadero Community
JEDI
Links
Swapping two variables without pointers or a third one Turn on/off line numbers in source code. Switch to Orginial background IDE or DSP color Comment or reply to this aritlce/tip for discussion. Bookmark this article to my favorite article(s). Print this article
18-Jun-03
Category
Algorithm
Language
Delphi 2.x
Views
109
User Rating
No Votes
# Votes
0
Replies
0
Publisher:
DSP, Administrator
Reference URL:
DKB
			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   var
4     var1: integer;
5     var2: integer;
6   begin
7   
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 swaps
22  // the contents of any 2 variables.
23  // The variables may be of any type but
24  // the sizeof the VARS must be passed in Len
25  //
26  // eg.  X1,X2 : integer;
27  //
28  //        SwapMem(X1,X2,SizeOf(Integer));
29  //
30  // ======================================== }
31  
32  procedure SwapMem(var Source, Dest; Len: integer);
33  begin
34    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;


			
Vote: How useful do you find this Article/Tip?
Bad Excellent
1 2 3 4 5 6 7 8 9 10

 

Advertisement
Share this page
Advertisement
Download from Google

Copyright © Mendozi Enterprises LLC