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 xor
ing 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
Windows Application Startup Error Exception Code: 0Xe0434352
Remove HTML Tags from String Including &Nbsp in C#
Is Ruby's Code Block Same as C#'s Lambda Expression
Predefined Type 'System.Valuetuple'2' Is Not Defined or Imported
Is the Use of Dynamic Considered a Bad Practice
Why Must I Provide Explicitly Generic Parameter Types While the Compiler Should Infer the Type
Converting Dd/Mm/Yyyy Formatted String to Datetime
C# Dictionary - One Key, Many Values
Deserializing JSON with Dynamic Keys
Does Xaml Have a Conditional Compiler Directive for Debug Mode
Getting the Current Tab's Url from Google Chrome Using C#
Updating Gui (Wpf) Using a Different Thread