> Why did they not extend the bitwise operators to include floating point values when they created C++?
Mostly because it doesn't make any sense - sure you can fiddle the bits, but the result doesn't make much sense as a floating point number.
Code:
#include <stdio.h>
int main ( ) {
union { float a; unsigned long b; } foo, bar;
foo.a = 1.234;
bar.a = 4.567;
foo.b ^= bar.b;
printf( "Result=%f\n", foo.a );
return 0;
}
Result=191198117439655548494113828686759198720.000000
Go figure....
It's strange the way people cling to the xor trick of swapping a pair of values, like its super efficient or magical in some way when in reality it isn't.
Here's a case in point
Code:
void s1 ( int a, int b ) {
a ^= b;
b ^= a;
a ^= b;
printf( "Swapped = %d, %d\n", a, b );
}
void s2 ( int a, int b ) {
int t = a;
a = b;
b = t;
printf( "Swapped = %d, %d\n", a, b );
}
Now with gcc -O, the first function still contains 3 xor operations.
In the 2nd function the swap has been completely eliminated by reducing the code to printf( "Swapped = %d, %d\n", b, a );
All you've managed to do is confuse the compiler just as much as the average reader.
So do yourself a favour and stick to the obvious code, then perhaps the compiler can make a half-decent job of optimising the code if there is an optimisation to be made.
Of course, since you (inaccurately) mentioned C++, you could always overload the ^ operator and implement something yourself. The integer only rules for bitwise operators came from C.