8

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;
}
  • 3
    Why don't you use `std::swap` in `` – Rapptz Sep 02 '12 at 16:58
  • Perhaps relevant: http://stackoverflow.com/questions/11529778/reason-why-custom-loop-is-faster-bad-compiler-unsafe-custom-code-lucklucky – sehe Sep 02 '12 at 17:01
  • Checking for x != y probably costs more than just exchanging two identical values. If this is an exercise for learning assembly code, fine; but the compiler will do just as good a job as you can here (in fact, better -- there's an unneeded instruction in the assembly code). – Pete Becker Sep 02 '12 at 19:03

2 Answers2

4

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;
}
perilbrain
  • 7,961
  • 2
  • 27
  • 35
-3

You can swap with Xor operation -

void swap(int *x, int *y)
{
     *x = *x ^ *y; /* #1 */
     *y = *x ^ *y; /* #2 */
     *x = *x ^ *y; /* #3 */
}
URL87
  • 10,667
  • 35
  • 107
  • 174