www.
linuxforu.
com | LINUX FOR YOU | MAY 2007
C M Y K
73
IIIII
t is assumed that the underlying machine follows 2’s
complement representation for integers and IEEE 754
floating point standard for floating point numbers.
Let us look at a well-known trick...
More
www.
linuxforu.
com | LINUX FOR YOU | MAY 2007
C M Y K
73
IIIII
t is assumed that the underlying machine follows 2’s
complement representation for integers and IEEE 754
floating point standard for floating point numbers.
Let us look at a well-known trick of swapping two integers
without using any temporary variables, which uses arithmetic
operators + and -:
void swap(int *i, int *j){
*i = *i + *j;
*j = *i - *j;
*i = *i - *j;
}
Yes, we know it works.
But does it really work in all cases?
How about this code:
int arr[5] = {10,20,30,40,50};
int *ip = &arr[3];
swap(ip,&arr[3]);
for(int i = 0; i<5; i++)
printf(“%d “, arr[i]);
// output: 10 20 30 0 50
So, when the elements to be swapped happen to refer
to the same location, swapping fails.
In the statement ‘*i=
*i + *j;’, the implicit assumption is that *i and *j point to
two different locations; this trick will not work if the
results of + and – operations are over-written.
Here is a
small test case just to demonstrate that:
int x = 10;
Less