J
Jason
Could someone please tell me if this is a bug or is it by
design?
I am using the triple XOR swap trick for two integers. I
show three "techniques", but only the first one works.
All three work in C++, but I get weird results in c#.
technique 1: (works in C#)
x ^= y;
y ^= x;
x ^= y;
technique 2 (doesn't work correctly in C#, does in C++)
x ^= y ^= x ^= y;
technique 3 doesn't work correctly in C#, does in C++)
x ^= (y ^= (x ^= y));
Here is some code you can cut and paste into vs.net.
Uncomment the parts in the Swap() function to try each
technique and see that only the first one works.
class Class1
{
[STAThread]
static void Main(string[] args)
{
int x = 1;
int y = 2;
Console.WriteLine("before swap");
Console.WriteLine("x: {0}", x);
Console.WriteLine("y: {0}", y);
Swap(ref x, ref y);
Console.WriteLine("\nafter swap");
Console.WriteLine("x: {0}", x);
Console.WriteLine("y: {0}", y);
}
public static void Swap(ref int x, ref int y) {
//Technique 1
// this works perfectly, just as in c++
x ^= y;
y ^= x;
x ^= y;
//Technique 2
// Put all on a single line.
// However, this produces incorrect results in
// C#, but works correctly in C++
//
//x ^= y ^= x ^= y;
//Technique 3
// This also doesn't work. C# should evaluate
// from the right (like C++), but something
// isn't working.
//
//x ^= (y ^= (x ^= y));
}
}
design?
I am using the triple XOR swap trick for two integers. I
show three "techniques", but only the first one works.
All three work in C++, but I get weird results in c#.
technique 1: (works in C#)
x ^= y;
y ^= x;
x ^= y;
technique 2 (doesn't work correctly in C#, does in C++)
x ^= y ^= x ^= y;
technique 3 doesn't work correctly in C#, does in C++)
x ^= (y ^= (x ^= y));
Here is some code you can cut and paste into vs.net.
Uncomment the parts in the Swap() function to try each
technique and see that only the first one works.
class Class1
{
[STAThread]
static void Main(string[] args)
{
int x = 1;
int y = 2;
Console.WriteLine("before swap");
Console.WriteLine("x: {0}", x);
Console.WriteLine("y: {0}", y);
Swap(ref x, ref y);
Console.WriteLine("\nafter swap");
Console.WriteLine("x: {0}", x);
Console.WriteLine("y: {0}", y);
}
public static void Swap(ref int x, ref int y) {
//Technique 1
// this works perfectly, just as in c++
x ^= y;
y ^= x;
x ^= y;
//Technique 2
// Put all on a single line.
// However, this produces incorrect results in
// C#, but works correctly in C++
//
//x ^= y ^= x ^= y;
//Technique 3
// This also doesn't work. C# should evaluate
// from the right (like C++), but something
// isn't working.
//
//x ^= (y ^= (x ^= y));
}
}