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

5
Contributors
6
Replies
8
Views
9 Years
Discussion Span
Last Post by Narue

>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.

well said

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.

Clear explanation.

Thank you very much

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.

good method for swapping the numbers.