What do the asterisks in this C language macro do?
#define asreal(x) (*((float *) &x))
I know about pointers in C, but it seems like the asterisks in this macro are being used for arithmetic? I am not sure exactly what is happening here.
Is the &x bitwise result being cast to a float pointer? Then why is there an additional asterisk outside of that expression?
CodePudding user response:
&x
- take address of x
(float*) &x
- cast it to float*
*((float *) &x)
dereference casted result (result type is float
)
(*((float *) &x))
- wrap it in paranthesis so it doesn't interfere with outside code
So basically, the code takes bytes in x
and reinterprets them as float
. Note that this macro would only be useful if
x
is afloat
already or- if it contains binary data equal to a valid
float
.
It cannot be used to convert int
value to float
(unless you try to use the bit representation of that int
, not the value) It will also break if called like asreal(x y)
or in quite a lot of other possiblities. I'm also not sure if it's defined behaviour in C, but if you are trying to "understand the machine", you are probably ready for certain UBs.