LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to exchange two variables without using a third (https://www.linuxquestions.org/questions/programming-9/how-to-exchange-two-variables-without-using-a-third-300322/)

skie_knite007 03-11-2005 04:29 AM

How to exchange two variables without using a third
 
Is it possible to exchage two variables without using temp?
(in C)

how can it be done.....!!!!!!!!!!

idefinehell 03-11-2005 04:42 AM

a,b be the two variables
(I)
temp=a;
a=b;
b=temp;

using an extra variable

and with out using an extra variable
(II)
a=a+b;
b=a-b;
a=a-b;

There r many ways 2 swap values of two variables
Hope this helps :-)

nulldevice 03-11-2005 04:48 AM

a^=b^=c^=a
but all these will work for integers only. when u say variable it has a larger context

Hko 03-11-2005 05:09 AM

Quote:

Originally posted by nulldevice
a^=b^=c^=a
But that still uses an extra variable: "c"....

This should work:
Code:

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



All times are GMT -5. The time now is 09:51 AM.