user1642124
user1642124

Reputation:

Unable to swap values

In the below code, output remains same in both cases,thanks for pointing what am I missing:-

Before Swap:-
a=10     b=512
After Swap:-
a=10     b=512

Following is the code, It compiles and runs without any problem:-

#include <stdio.h>
int swap(int* x, int* y)
{
    if(x != y)
    {
        _asm
        {
            mov eax,[x]; x into eax
            mov ebx,[y]
            mov [x],ebx;swapping now
            mov [y],eax
        }
    }
    return 0;
}

int main () {
  int a=10,b=512;
  printf("Before Swap:- \na=%d\t b=%d\n",a,b);
  swap(&a,&b); 
  printf("After Swap:- \na=%d\t b=%d",a,b);//Value remains same
  return 0;
}

Upvotes: 8

Views: 251

Answers (2)

URL87
URL87

Reputation: 11012

You can swap with Xor operation -

void swap(int *x, int *y)
{
     *x = *x ^ *y; /* #1 */
     *y = *x ^ *y; /* #2 */
     *x = *x ^ *y; /* #3 */
}

Upvotes: -3

perilbrain
perilbrain

Reputation: 8197

No indirection on variables inside assembly block wont work.Instead take addresses in registers and then only try indirection.It will rather break into something like mov eax, DWORD PTR _x$[ebp]

#include <stdio.h>
int swap(int* x, int* y)
{
    if(x != y)
    {
        _asm
        {
            mov eax,x
            mov ebx,y
            mov ecx,[ebx]
            xchg ecx,[eax]
            xchg [ebx],ecx
        }
    }
    return 0;
}

int main () {
  int a=10,b=512;
  printf("Before Swap:- \na=%d\t b=%d\n",a,b);
  swap(&a,&b);
  printf("After Swap:- \na=%d\t b=%d",a,b);
  getchar();
  return 0;
}

Upvotes: 4

Related Questions