:icon_smile:
hi all!!
i am a newbie in this forum.
can u solve me the problem of interchanging/swapping the value of two varibles without using the third variable...
thanks..

Re: Swapping Without Third Variable 80 80

http://www.catb.org/~esr/faqs/smart-questions.html#writewell

Yes you can http://c-faq.com/expr/xorswapexpr.html
But that is a dumb trick which ceased to be of any importance when we came down from the trees and started using high level programming languages.

Re: Swapping Without Third Variable 80 80
Member Avatar

Here's anothe way

x -= y;
y += x;        // y becomes x
x = (y - x);    // x becomes y
Re: Swapping Without Third Variable 80 80

Ever hear of arithmetic overflow ?

- it would be OK on unsigned types.
- it would be liable to arithmetic overflow on signed types.
- for floating point types, expect both to become corrupted, especially if values differ greatly in magnitude
- utterly hopeless as an approach for any other type.

Re: Swapping Without Third Variable 80 80

Is it that time of year again? :icon_rolleyes:

Re: Swapping Without Third Variable 80 80

I would really suggest to use the temp variable to swap two values. Cos the swapping variables without third variable such as using the arithmetic operators. This would really very help only when you wanted to swap unsigned integers. Apart from that it is not a recommended at all. If anything other unsigned integers you need to use the temp variable to swap. But in over all the latter would be efficient way of doing it.

ssharish

Re: Swapping Without Third Variable 80 80

I have another way to solve your problem

1. x=x+y;
2. y=x-y;
3. x=x-y;

Re: Swapping Without Third Variable 80 80

> I have another way to solve your problem
Apparently, you didn't read reply #4

Be a part of the DaniWeb community

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