What is the difference between '* (<type> *) & x' and 'x'?
What's the difference between
int i = 123; int k; k = *(int *) &i; cout << k << endl; //Output: 123 and
int i = 123; int k; k = i; cout << k << endl; //Output: 123 Both of them give the same conclusion, but is there any difference?
(I found the first Quake3 code snippet of the fast reverse square root)
+4
3 answers
In Q3:
float Q_rsqrt( float number ) { long i; float x2, y; const float threehalfs = 1.5F; x2 = number * 0.5F; y = number; i = * ( long * ) &y; // evil floating point bit level hacking i = 0x5f3759df - ( i >> 1 ); // what the fuck? y = * ( float * ) &i; y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed return y; } As I understand it, you are interested in the following line:
i = * ( long * ) &y; y is a float , and i is a long . So this is a reinterpretation for a floating point bitmap as an integer bitmap.
+7
No, there is no difference, both assignments essentially copy the int bit from the memory storing i into memory k .
Sometimes such tricks are used when the types of the source and destination variables are different, but it's just int to int .
I think that a smart enough compiler should generate the same code for both versions.
+2