From compiled code point of view references are pointers (that's why they behave like pointers). It's compiler that doesn't let you manage them as pointers in your C++ code (C++, not C because C has not references).
For this reason yes, you have pointers then you have to deference them to swap variable values. For an example of (working) assembly code take a look to this post here on SO.
Moreover I'd suggest to use __declspec(naked)
too so you can write your own short prolog/epilog (otherwise performance benefit of a custom assembly function is pretty small, if there is a benefit at all).
That said you don't even need to use a register for that and you can do it with stack, just pop
in reverse order:
__declspec(naked) void swap_fast(int32& a, int32& b)
{
__asm
{
push [a]
push [b]
pop [a]
pop [b]
}
}
Same can be done through a register (as temporary variable as you're doing, just do not deference pointers) or with xchg
, I suppose out there there are a plethora of different algorithms to perform swap in C, C++ and assembly.
Important note about performance: actually I don't know which method is faster; probably a macro with a temporary (register
?) variable has same speed as our smart assembly code because compiler will be free to optimize generated assembly much better...