English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

6 answers

If you define a function called swap(x , y) , then the function itself can be coded as :

swap = x ;
x = y ;
y = swap ;
return

I found the following in the link given below :

void swap(int *a, int *b)
{
*a = *a ^ *b;
*b = *b ^ *a;
*a = *a ^ *b;
}

where the ^ symbol stands for XOR.

2007-12-28 07:30:01 · answer #1 · answered by NARAYAN RAO 5 · 0 1

Assuming that operations + and - are defined for two variables a and b and that a > b then the following assignment statements will swap the values.
a = a + b
b = a - b
a = a - b

Obviously, this won't work if a and b are string variables or variables of type for which + and - operations aren't arithmetical

2007-12-28 15:38:23 · answer #2 · answered by Jaspreet J 1 · 0 0

Without using a 3rd variable of any kind:

Let x,y be the given variables. Then
x = x+y;
y = x - y;
x = x - y;

(I think that's C/C++ syntax, but it hardly matters!)

Note this only works if x and y are numerical data; if not, I don't think the task is possible.
§

2007-12-28 15:33:57 · answer #3 · answered by jeredwm 6 · 4 0

Without C hacks? Can't. If you may, use a function, named, say, swap(), to hide the temp variable.

2007-12-28 15:36:14 · answer #4 · answered by jcastro 6 · 0 1

a=10
b=20

a=a+b;
b=a-b;
a=a-b;

is the code.

2007-12-28 22:37:05 · answer #5 · answered by The Ranger 6 · 0 0

y = (x XOR y);
x = (x XOR y);
y = (x XOR y);

( y XOR y = 0, 0 XOR y = y again. )

2007-12-28 15:35:54 · answer #6 · answered by gjmb1960 7 · 0 1

fedest.com, questions and answers