I tried to swap 2 integer numbers without using an additional variable as a traditional swap.
Is it legal in C++? My VC compiler doesn't complain nor gives any warning about it. If so, how can I improve this script?
#include <iostream>
int main()
{
int a = 20;
int b = 66;
// before swapping
std::cout << a << ' ' << b << '\n';
// swap
a ^= b ^= a ^= b;
// after swapping
std::cout << a << ' ' << b << '\n';
}
For this code:
int a = 20;
int b = 66;
a ^= b ^= a ^= b;
Assembler output for VC++ 2013:
_b$ = -20 ; size = 4 _a$ = -8 ; size = 4 mov DWORD PTR _a$[ebp], 20 ; 00000014H mov DWORD PTR _b$[ebp], 66 ; 00000042H mov eax, DWORD PTR _a$[ebp] xor eax, DWORD PTR _b$[ebp] mov DWORD PTR _a$[ebp], eax mov ecx, DWORD PTR _b$[ebp] xor ecx, DWORD PTR _a$[ebp] mov DWORD PTR _b$[ebp], ecx mov edx, DWORD PTR _a$[ebp] xor edx, DWORD PTR _b$[ebp] mov DWORD PTR _a$[ebp], edx
For this code:
int a = 20;
int b = 66;
int t = a;
a = b;
b = t;
Assembler output for VC++ 2013:
_t$ = -32 ; size = 4 _b$ = -20 ; size = 4 _a$ = -8 ; size = 4 mov DWORD PTR _a$[ebp], 20 ; 00000014H mov DWORD PTR _b$[ebp], 66 ; 00000042H mov eax, DWORD PTR _a$[ebp] mov DWORD PTR _t$[ebp], eax mov eax, DWORD PTR _b$[ebp] mov DWORD PTR _a$[ebp], eax mov eax, DWORD PTR _t$[ebp] mov DWORD PTR _b$[ebp], eax
std::swap
. – CodesInChaos Jan 8 '15 at 15:40