1.11M Members

exchange 2 variables values without using 3rd variable.

 
-2
 

How can I exchange 2 variables values without using any 3rd temporary variable.

 
0
 

>How can I exchange 2 variables values without using any 3rd temporary variable.
Most likely your teacher is expecting this:

a ^= b;
b ^= a;
a ^= b;

But I'd recommend you find a new teacher because your current one is likely too focused on archaic trivialities and bad practices to teach you anything worthwhile.

 
1
 

How can I exchange 2 variables values without using any 3rd temporary variable.

Let's say you have A=0x10100000 and B=0x00001010 then this is what you do to swap the two variables without using a third variable.

Step 1
_____

(A) Exclusive OR (B), when you do this here's what happens

(A) 10100000
(B) 00001010
------------------
(A) 10101010 XOR Result - contents of A
(B) 00001010 B is unchanged

Step 2
_____

Now (B) Exclusive OR (A), when you do this here's what happens

(B) 00001010
(A) 10101010
------------------
(B) 10100000 XOR Result - contents of B
(A) 10101010 A is unchanged - same as after Step 1

Step 3
_____

Now (A Exclusive OR (B), when you do this here's what happens

(A) 10101010
(B) 10100000
------------------
(A) 00001010 XOR Result - contents of A
(B) 10100000 B is unchanged - same as after Step 2

Finally A has 00001010 and B has 10100000 (what you wanted, you have swapped them) and you did not use an itermediate variable.

Question Answered as of 5 Years Ago by Narue and iyercb
 
0
 

Thank you very much

 
0
 

Very good, now try it with something else, like a float or a struct or a pointer.

It's a cheap trick, not programming knowledge.

 
-1
 

good method for swapping the numbers.

 
1
 

>good method for swapping the numbers.
No, it's not. It's brittle, often slower than the conventional method, and due to compiler optimizations the chances that it saves memory over the equivalent swap with a temporary are actually quite slim. This trick may have been useful twenty or thirty years ago, but now it's just a stupid way for stupid people to show of their knowledge of stupid trivia.

You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article