简体   繁体   中英

Swap values with XOR

This is a valid way to swap values in C++ and in C#.

X ^= Y;
Y ^= X;
X ^= Y;

And this is a valid way to swap values in C++.

X ^= Y ^= X ^= Y;

But why is this not working in C# ?

int X = 3;
X = X + X++; // X = 6;

int X = 3
X = X++ + X; // X = 7;

Similarly:

int X = 3;
int Y = 5;
X = (Y ^= X ^= Y)^X; // X = 5

However:

int X = 3;
int Y = 5;
X = X^(Y ^= X ^= Y); // X = 0

Unfortunately:

X = X^(Y ^= X ^= Y) is an equivalence of X ^= Y ^= X ^= Y

I checked the MSIL generated by the compiler. In the first case, everything is normal - push x, push y, xor, pop x etc. In the 2nd case it starts with push x, push y, push x, push y and ends up using the initial value of x in the last xor:

ldloc.0
ldloc.1
ldloc.0
ldloc.1
xor
dup
stloc.0
xor
dup
stloc.1
xor
dup
stloc.0

I tried generating ASM of C++ code and decompiling the .NET code here is what I got:

ASM

mov eax, DWORD PTR _X$[ebp]
mov ecx, DWORD PTR _Y$[ebp]
mov edx, DWORD PTR [eax]
xor edx, DWORD PTR [ecx]
mov eax, DWORD PTR _X$[ebp]
mov DWORD PTR [eax], edx
mov ecx, DWORD PTR _Y$[ebp]
mov edx, DWORD PTR _X$[ebp]
mov eax, DWORD PTR [ecx]
xor eax, DWORD PTR [edx]
mov ecx, DWORD PTR _Y$[ebp]
mov DWORD PTR [ecx], eax
mov edx, DWORD PTR _X$[ebp]
mov eax, DWORD PTR _Y$[ebp]
mov ecx, DWORD PTR [edx]
xor ecx, DWORD PTR [eax]
mov edx, DWORD PTR _X$[ebp]
mov DWORD PTR [edx], ecx

from my little knowledge of assembly I think that this basically is:

X ^= Y;
Y ^= X;
X ^= Y;

C# (Generated with JetBrains dotPeek)

int& local1 = @X;
int num1 = ^local1;
int& local2 = @Y;
int num2 = ^local2;
int num3 = X ^= Y;
int num4;
int num5 = num4 = num2 ^ num3;
^local2 = num4;
int num6 = num5;
int num7 = num1 ^ num6;
^local1 = num7;

Not sure of the meaning of &,^,@ , but I think that this is basically:

int xStartingValue = X;
X ^= Y;
Y ^= X;
X = xStartingValue ^ Y;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM