I've been reading about swapping the content of variables without using a temporary variable and besides the famous xor algorithm I've found out about the XCHG instruction from assembly on x86. So I wrote this code:
void swap(int *left, int *right){
__asm__ __volatile__(
"movl %0, %%eax;"
"movl %1, %%ebx;"
:
: "r" (*left), "r" (*right)
);
__asm__ __volatile__(
"xchg %eax, %ebx;"
);
__asm__ __volatile__(
"movl %%eax, %0;"
"movl %%ebx, %1;"
: "=r" (*left), "=r" (*right)
);}
It does work but then I realized the XCHG instruction is not necessary at all.
void swap(int *left, int *right){
__asm__ __volatile__(
"movl %0, %%eax;"
"movl %1, %%ebx;"
:
: "r" (*left), "r" (*right)
);
__asm__ __volatile__(
"movl %%ebx, %0;"
"movl %%eax, %1;"
: "=r" (*left), "=r" (*right)
);}
The second function works too but nobody seems to mention swapping variables using registers so is this code considered wrong and in reality it's not really working properly? Am I missing something?
I realize this will work only for x86 but since most people have a intel x86 processor could this code be be used in any real world programming? I realize that this probably won't be any faster than a regular swap with a temporary variable but i'm asking from a theoretical point of view. If during a test or an interview someone asks me to write a function in C to swap values for a x86 machine without using a temporary variable would this code be valid or it's complete crap? Thanks you.