How to swap two variables without using a third variable & pointer?

Recommended Answers

All 5 Replies

Any good reason to do that?
Using temporary variable will be much better.

If you are using it for educational purposes then there are two options mentioned above by Mr. iamthwee.

And if using for some real application and u think that doing the swap without temporary variable would reduce the space required or the time then do think again. Its not that way. Current compilers are so optimised that using a temp varible doesnt even a fractiion affect the program.

But still if u are so peculiar about performance then usign Assembly Language is the way to go.

So u have two options:
1) use normal temp variable
2) use assembly language procedures

since using XOR and += have their own shortcomings.

> How to swap two variables without using a third variable & pointer?
This ceased to be interesting when we came down from the trees and started using high level programming languages.

If your "teacher" somehow thinks this is a good idea you need a better teacher.

http://en.wikipedia.org/wiki/Xor_swap
Way too many special cases for it to be considered anything more than a party trick.

Another recent post on the same subject.
http://www.daniweb.com/techtalkforums/thread49488.html

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.