Maybe I have missed something about functions or something else?
I use VS 2010.
Here is my code:
#include <iostream>
void swap (int& a, int& b)
{
__asm push a
__asm push b
__asm pop a
__asm pop b
std::cout << "Inline function check: a=" << a << " b=" << b << "\n\n";
}
void main()
{
int arg1=1, arg2=9000;
std::cout << "Before swap we have: a=" << arg1 << " b=" << arg2 << "\n\n";
swap(arg1, arg2);
std::cout << "After swap we have: a=" << arg1 << " b=" << arg2;
std::cin.get();
}
When you pass by reference with Visual Studio, the compiler passes the address of the referenced variable. Your swap is actually swapping the addresses that were passed to the swap function; it’s not actually swapping the contents.
In order to swap the contents, you would need to dereference the pointers. Unfortunately, the compiler won’t allow you to do this directly, so you’ll have to use registers.
Here is a short example. This is just a demonstration; swapping the two variables can be done with far fewer instructions if you access the stack directly, instead of using
aandb. It’s important to note that memory can only be modified by using a register.