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

Recommended Answers

All 6 Replies

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

commented: well said +17

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.

commented: Clear explanation. +6

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.

commented: No it isn't, it's a cheap trick from ASM days, not a useful technique for a HLL -4

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

commented: Agreed +4
commented: Well said +17
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.