Swap Two Variables Without Using a Temporary Variable

Swap two variables without using a temporary variable

First of all, swapping without a temporary variable in a language as C# is a very bad idea.

But for the sake of answer, you can use this code:

startAngle = startAngle + stopAngle;
stopAngle = startAngle - stopAngle;
startAngle = startAngle - stopAngle;

Problems can however occur with rounding off if the two numbers differ largely. This is due to the nature of floating point numbers.

If you want to hide the temporary variable, you can use a utility method:

public static class Foo {

public static void Swap<T> (ref T lhs, ref T rhs) {
T temp = lhs;
lhs = rhs;
rhs = temp;
}
}

Swap two numbers without using temp variable

It creates a tuple on the right hand side of the = then deconstructs it (into different variables) on the left hand side. See this page of the fine manual

Effectively the compiler is writing something like this for you, if you're familiar with the Tuple<T1,T2> introduced years ago:

var t = new Tuple<int,int>(a, b); //create with Item1 = a and Item2 = b
b = t.Item1;
a = t.Item2;

Exactly what code it will be writing under the hood, I don't know, but that will be the spirit of it; to create a temporary (probably Value)Tuple, assign a and b to it then get them out again in the opposite order

When would you swap two numbers without using a third variable?

At this point it's just a neat trick. Speed-wise if it makes sense though your compiler will recognize a normal swap and optimize it appropriately (but no guarantees that it will recognize weird xoring and optimize that appropriately).

Swap two numbers without using another variable

use the following concept

int a=4 ;
int b=3 ;

a=a+b ; // a=7
b=a-b ; // b=7-3=4
a=a-b ; // c=7-4=3

Which is better to swap numbers? Using temporary variable or without it? Does it even matter?

I will say definitely with a temp variable i.e. your first option. If you refer to your second example you have done total three operation. For each operation your java virtual machine generate equivalent assembly operation. But in your first option with a temp variable you are just swapping the values. Hence very minimal assembly operation only to read from address and write into address.



Related Topics



Leave a reply



Submit