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.

Recommended Answers

All 6 Replies

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?

The code I posted does not change the pointers, only the values to which they point. If you want to use xor then do so.

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.

Swap Two numbers using Stack in assembly language

.MODEL SMALL
.STACK 100H
.CODE
MAIN PROC
        MOV AX,'9'
        MOV BX,'4'
        PUSH AX
        PUSH BX
        POP  AX
        POP BX
        MOV DX,AX
        MOV AH,2
        INT 21H
        MOV DX,BX
        INT 21H
        MOV AH,4CH
        INT 21H
        MAIN ENDP
        END MAIN
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.