Whats the difference between
and...Code:void swap(int* a,int* b)
{
int x=*a,y=*b;
x=x+y;
y=x-y;
x=x-y;
*a=x; *b=y;
return;
}
Code:void swap(int* a,int* b)
{
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
return;
}
Printable View
Whats the difference between
and...Code:void swap(int* a,int* b)
{
int x=*a,y=*b;
x=x+y;
y=x-y;
x=x-y;
*a=x; *b=y;
return;
}
Code:void swap(int* a,int* b)
{
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
return;
}
Functionally, they both have the same net effect (presumably to perform a swap in a rather roundabout way, assuming no arithmetic overflow). The first version simulates call by copy-restore (a.k.a. value-result), the second just uses pointer arguments to simulate call by reference, as is the usual method in C.Quote:
Whats the difference between
Does it matter?
They're both broken attempts to swap two integers.
The first fails miserably in attempting to avoid creating one temporary, by instead creating two temporaries.
Try calling the second one with swap(&a,&a)
Oh yes, but that means that I am wrong to say that they have the same net effect. Call by copy-restore avoids this problem.Quote:
Try calling the second one with swap(&a,&a)
I implemented the second in my code and it didn't work...
I replaced it with first and it works fine....
A quick test shows that it works, with the caveat pointed out by Salem.Quote:
I implemented the second in my code and it didn't work...
I hope that you are actually implementing swap() for your actual code with the more straightforward implementation.
How about just
It does exactly what you think it should do, has no unexpected side effects, and doesn't rely on the overflow behaviour of your machine.Code:int temp = *a;
*a = *b;
*b = temp;
Oh, and stop paying attention to dumb programming tricks.