December 05, 2012

Swapping Numerical Values Without Copy

Similarly to the XOR method for integers, here is a clever way to swap any two numerical values without copy (the code is in C, but works the same for any language of course...):


double a = 157648.13;
double b = 96871.84;

printf("%.4f %.4f\n", a, b);

a = a + b;
b = a - b;
a = a - b;

printf("%.4f %.4f\n", a, b);

Just be careful with overflows, and enjoy ;)

No comments:

Post a Comment