Jack said:
On Mon, 29 Sep 2003 21:18:07 -0700, Noah Roberts
Case 1:
double d1 = 3.14159;
double d2 = 3.6864;
double swap_contents_with_bitwise_operators(double d1, double d2)
{
double result = /* please fill in the blank */ ;
return result;
}
I was pretty sure this was the case but I tested it anyway:
test.cpp:11: error: invalid operands of types `double' and `double' to
binary `
operator^'
test.cpp:11: error: in evaluation of `operator^=(double, double)'
and more of the same...
Correct me if my compiler is non-standard. I think C would barf also.
Yes, there is probably a good reason why bitwise operators are not
allowed on floating point types.
Case 2:
int swap_ints(int *a, int *b)
{
*a ^= *b;
*b ^= *a;
}
Yes, you never ever want to do that.....
int x = 27;
swap(&x, &x);
because the pointers might point to the same thing. This also would be
undefined:
x ^= x;
or
x += x; // yet you won't be saying += is a bad operation...
I believe even 'x = x' is undefined.
However, this sort of code is completely safe and quite useful:
int x = 27, y = 34;
x ^= y; y ^= x; x ^= y; // We know what x and y are after this...
For instance, the easiest fastest way to highlight text in a GUI is to
to use xor operators. You can also quickly switch colors with an xor
operation as used in computer games (maybe not anymore):
some_integral_type color_key = what_i_want ^ what_is_there;
xor_draw_area(area, color_key); // switch
xor_draw_area(area, color_key); // switch back.
Also, you can make your function safe:
void swap(int *x, int *y)
{
if (x==y) return; // no need to swap and it would be undefined if we
did...
... // but it is safe otherwise...(assuming we own the memory
pointed to by x and y which you also want to check).
}
...not to mention that anyone who wrote this in production would be
shot on sight. Well, OK, at the code inspection.
Nobody really uses it to swap value x and y, but often you want to
quickly change and revert values and xor is a great way to do that. It
is used a lot in XFree86 and probably just about any GUI system around.
NR