|
-
March 28th, 1999, 11:56 AM
#1
But ICB is partially right
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?
-
March 28th, 1999, 03:00 PM
#2
Re: But ICB is partially right
I posted a solution that works and meets all requirements....
rgards
Hans Wedemeyer
-
March 28th, 1999, 08:45 PM
#3
Re: But ICB is partially right
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|