Click to See Complete Forum and Search --> : But ICB is partially right


Bore
March 28th, 1999, 10:56 AM
Ok, I wasn't going to get drawn into this conversation, but ICB's claim that swap(x,x) won't work had me bothered.

His/her claim is true if we implement the function swap():

void swap(int &a,int &b)

and we call it thus:

main()

{

int a = 7;

int b = 8;

swap(a,a);

}

But note that it works fine if we call it thus:

main()

{

int a = 7;

int b = 7;

swap(a,b);

}

I couldn't tell which situation ICB meant when (s)he said, "swap(x,x)". So after thinking about it way too long, I

imagined a situation where swap() would realistically be called as in my first example:

main()

{

int *a = GetIntFromSomeListInMemory();

int *b = GetIntFromSomeListInMemory();

// Here it turns out that a == b

swap(*a,*b);

}

One solution is to implement swap() like this:

inline void swap(int *a,int *b)

{

if(a == b)

return;

*a ^= *b;

*b ^= *a;

*a ^= *b;

}

But then wouldn't the extra instructions take up just as must space as a temp variable? I've been in the risc world for

a while, so my x86 assembly is rusty. So I agree, there's not a good *general* solution, but it's still quite useful

case-by-case if memory is really a problem.


Anyone hiring obsessive software engineers?

Hans Wedemeyer
March 28th, 1999, 02:00 PM
I posted a solution that works and meets all requirements....


rgards

Hans Wedemeyer

Hans Wedemeyer
March 28th, 1999, 07:45 PM
Of course the xor version actually used three registers ( compiled with /Fa shows that )

my Version ( posted here in this thread ) goes beyond the spec's and handles full 32 bit

unsigned int's as well, the xor version can't do that.....


Here's the output of the xor program


xor 4294967295 5

a=-1 b=5

a=5 b=-1


Falls flat on it's face when it comes to handling my bank account figures... ( I wish !)


regards

Hans Wedemeyer