Preconditions:
Addresses of 2 integer variables are on the stack as the parameters.

Sample c call:       swap( &num1, &num2);

You must implement the following C swap function:

/*
  Swaps the two values pointed to by x_ptr and y_ptr.
*/
void swap (int *x_ptr, int *y_ptr)
{
   if (x_ptr != y_ptr) 
   {
      *x_ptr ^= *y_ptr;  /* note that ^ means xor */
      *y_ptr ^= *x_ptr;
      *x_ptr ^= *y_ptr;
   }
}

Postconditions:
The values of the two integer parameters have been exchanged.

Edited 3 Years Ago by Nick Evan: Fixed formatting

swapping two integers in assembly is a lot easier than the code you posted. This assumes 32-bit integers on Intel family of 32-bit/64-bit processors

mov esi,x_ptr
mov eax,[esi]
mov edi,y_ptr
mov edx,[edi]
mov [esi],edx
mov [edi],eax

I was hoping to do this with the xor commands.
Also, at the end of this is the x pointer now pointing to what the y pointer was originally pointing to and vice versa?

I'm fairly new to Assembly myself, is there a reason something like this wouldn't work?

xchg eax, ebx ; swap Value1 and Value2

I'm fairly new to Assembly myself, is there a reason something like this wouldn't work?

xchg eax, ebx ; swap Value1 and Value2

That exchanges the two integers in the registers all right, but doesn't save the values in the memory addresses of the two pointers. The results still have to be saved at those addresses. But that xchg instruction isn't needed for the simple swap in this program -- wasted CPU time.

Edited 5 Years Ago by Ancient Dragon: n/a

This question has already been answered. Start a new discussion instead.