I'm not able to understand some typecasting syntaxes. For eg.
float f=7.0;
short s=*(short *)&f;
What's happening here short s=*(short *)&f
? Looks like we're casting something
as a pointer to a short and then initializing s
to value stored in the address pointed to by something
.
Now, this something
looks like the address of variable f
. So if something
= address of f
, it appears to me that we are making address of f
as a pointer to some short and then de-referencing it. I know that what I've stated is wrong, but I just can't seem to visualize it.
Thanks.
This syntax would make the most sense if short
was the same size as float
and even so, there would remain a problem with "strict aliasing rules".
It is used to interpret the bits of the float
f as representing an integer. It is used to circumvent the fact that s = (short) f;
would be interpreted as a conversion to integer. Truncation, I believe.
Your interpretation is correct. It's essentially forcing the compiler to treat the memory storing f
as if it were actually treating a short
. The result of this will be platform-dependent. This is very different to short s = (short)f;
, which will just perform a nice conversion, and is well-defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With