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?
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?