[C] swapping vars
Posted: Sat 05 May, 2007 7:50 pm
I found a piece of code on wikipedia:
I almost fell from my chair!
using an extra variable??
this is more like it:
It's not like it really matters, but using a local variable where you don't need one is evil. Ofcourse you could just use the evil code if you use a good optimizer..
In good ol' z80 assembly you don't have arbitrary xors, but you can do something else: (swap (de) and (hl) )
Code: Select all
/* function used for swapping values of two variables */
void swap(int *a, int *b)
{
int c = *a;
*a = *b;
*b = c;
}
using an extra variable??
this is more like it:
Code: Select all
/* function used for PROPERLY swapping values of two variables */
void swap(int *a, int *b)
{
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
In good ol' z80 assembly you don't have arbitrary xors, but you can do something else: (swap (de) and (hl) )
Code: Select all
ld a,(de)
ldi
dec hl
ld (hl),a